tags:

views:

57

answers:

2

I would like to do something like this:

DoCmd.OpenQuery "select * from some_table;"

How would I do this?

Please keep in mind I don't want to create a new query, save it, and run it. I just want to type the select statement in the VBA code and run it.

+4  A: 

If you just want to get a max value, the DMax-Function should do the trick:

myVariable = DMax("fee", "courses", "region = 'UK'")

(corresponds to SELECT MAX(fee) FROM courses WHERE region = 'UK').

Heinzi
+1  A: 

You can run a query to retrieve a single value with something like this:

Set rst = CurrentDB.OpenRecordset("Select Max(myCol) FROM myTable")
myValue = rst(0).Value

Which you can shorten down to one line like this:

lngValue = CurrentDB.OpenRecordset("Select Max(myCol) FROM myTable")(0)
voon
Thou shalt close thy recordsets after using them, or thy memory will not be released (see, e.g., KB 209847).
Heinzi
I do the latter all the time to look up a single value. It's not in any danger because it's based on CurrentDB, which always goes out of scope as soon as it's called (i.e., each call to it gets a different object and if you didn't persist the result in the first call, it won't exist after the line where it's called).
David-W-Fenton
@David: Except that your database will grow to hundreds of megabytes in size.
SLaks
@Slaks: on what basis do you make that assertion? It is completely false and without any basis at all. The only structures created with that are memory structures, which don't have any effect whatsoever on the size of the database file. Using a temporary QueryDef is a different issue, but that's not what was suggested.
David-W-Fenton
@David: Experience. Five years ago, I had a couple of 300MB MDB files as a result of this practice. (However, it may have used QueryDefs; I don't remember) http://support.microsoft.com/kb/209847
SLaks
I already addressed the issues in the cited Knowledge Base article -- by using CurrentDB, you guarantee that the recordset goes out of scope immediately on the next line, and can't use extra memory. Even then, I think the article is completely wrong in regard to the allegation that it bloats the database. I've never seen such a thing *except* with temporary QueryDefs, which definitely *do* bloat the database (but not by very much). The idea of any of these things bloating to 300MBs seems completely far-fetched to me.
David-W-Fenton