Update Query's SQL in VB (1 Viewer)

flemmo

Registered User.
Local time
Today, 06:03
Joined
Apr 26, 2006
Messages
69
I have a form with a button. When I click on the button I want to update the Sql in that query to something else - in a similar way to updating a form's recordsource I guess?

Thanks
 

pbaldy

Wino Moderator
Staff member
Local time
Yesterday, 22:03
Joined
Aug 30, 2003
Messages
36,133
Search on QueryDef which should turn up the appropriate code.
 

flemmo

Registered User.
Local time
Today, 06:03
Joined
Apr 26, 2006
Messages
69
will do. Thanks for the quick reply.
 

pbaldy

Wino Moderator
Staff member
Local time
Yesterday, 22:03
Joined
Aug 30, 2003
Messages
36,133
No problemo; post back if you get stuck.
 

flemmo

Registered User.
Local time
Today, 06:03
Joined
Apr 26, 2006
Messages
69
Guess what? I'm stuck lol!

As an example I want to update the Query "MyQuery" with "SELECT * from CUSTOMERS". How would I do this? I was playing around with the following but it doesn't work so...

Code:
Dim NewSQL As QueryDef
Set NewSQL = CreateQueryDef("SELECT * from CUSTOMERS",MyQuery)

Thanks
 

flemmo

Registered User.
Local time
Today, 06:03
Joined
Apr 26, 2006
Messages
69
Think I've cracked it?

Code:
 Dim db As Database
 Dim qdf As QueryDef
 Dim strSQL As String
 Set db = CurrentDb
    
 strSQL = "SELECT * FROM CUSTOMERS;"
 db.QueryDefs("MyQuery").SQL = strSQL
 

pbaldy

Wino Moderator
Staff member
Local time
Yesterday, 22:03
Joined
Aug 30, 2003
Messages
36,133
Try this to change the SQL of an existing query:

Code:
    Dim db As DAO.Database
    Dim qdf As DAO.QueryDef
    
    Set db = CurrentDb
    Set qdf = db.QueryDefs("MyQuery")

    qdf.SQL = "SELECT * from CUSTOMERS"

    qdf.close
    Set db = Nothing
    Set qdf = Nothing
 

pbaldy

Wino Moderator
Staff member
Local time
Yesterday, 22:03
Joined
Aug 30, 2003
Messages
36,133
Looks like we were posting at the same time, and offhand it looks like yours would also work.
 

Users who are viewing this thread

Top Bottom