Access VBA SQL fails to execute - vba

Using the following code that generates
Error:(2342) A Run SQL action requires an action consisting of an SQL
statement
Here is the code:
Dim Lping As Variant
Lping = "SELECT dbo_Log_Table.LogID"
Lping = Lping + " FROM dbo_Log_Table"
Lping = Lping + " WHERE (((dbo_Log_Table.LogID)=1))"
DoCmd.SetWarnings False
DoCmd.RunSQL Lping
DoCmd.SetWarnings True
The SQL is copied from the QBE grid and executes from there. I have other such code, but can't see the problem with this.
Thanks in advance
JPL

The problem is that DoCmd.RunSQL runs action statements: Insert, Update, Delete. A select statement doesn't do anything. You have no way of obtaining the results of this query and using them and thus RunSQL doesn't even let you waste your time doing it.
If you want to use the results of this query you'll need to create a QueryDef, a query object and use that, or explicitly generate a recordset. Either way the Query needs to get into a recordset to be used.

Related

Pass Through Query Won't Run From Command Line

I created a pass through query in Access.
All it says is .
sp_Submit ''
If I click on it directly it runs the SSMS stored procedure which just changes some test tables.
However if I run it in VBA it does not work. It doesn't error out or anything, it just does not work.
I have tried
sSQL = "sp_Submit '" & Me.cboNumber & "'"
and
sSQL = "sp_Submit '"
Please not the stored procedure isn't doing anything much at this point. I have it testing some stuff. It just deletes everything in one table and inserts it in another.
What am I doing wrong? I've used this in the past and it has worked so I'm not sure why it doesn't work this time. The stored procedure itself is set up to accept one variable but it doesn't actually do anything with it (yet.).
Thank you.
Given what you have to far, then you should be able to edit the saved pass though query with
Sp_Submit 'test'
Assuming the 1 paramter is text. If the parameter is to be a number, then
Sp_Submit 123
At this point, you have to save that query. Now click on it, does it run correctly?
And in place of clicking on the query, you can certainly do
CurrentDB.execute "name of saved query goes here"
However, keep in mind that a PT query is raw T-SQL. What executes runs 100% on the server. This means that such query(s) cannot contain references to any form, or anything else. So you have to “pre-process” or create the value you wish to pass and modify the PT query. So your code of creating the SQL you have looks correct, but you then have to take that sql string and "set" the PT query.
The most easy way to do this is with code like this:
With CurrentDb.QueryDefs("MyPass")
.SQL = "sp_Submit '" & Me.cboNumber & "'"
.Execute
End With
Of course if the PT query returns records, then you would go:
Dim rstRecords As DAO.Recordset
With CurrentDb.QueryDefs("MyPass")
.SQL = "sp_Submit '" & Me.cboNumber & "'"
.ReturnsRecords = True
Set rstRecords = .OpenRecordset
End With
And to be fair, you likely should set “returns” records = false in the first example. You can do this in the property sheet of the save query, or in code like this:
With CurrentDb.QueryDefs("MyPass")
.SQL = "sp_Submit '" & Me.cboNumber & "'"
.ReturnsRecords = False
.Execute
End With
Note that you can use the one PT query over and over in your code. So once you ceated that one PT query, then you can use it to pass any new sql you wish, such as:
Dim rstRecords As DAO.Recordset
With CurrentDb.QueryDefs("MyPass")
.SQL = "select * from tblHotels"
.ReturnsRecords = True
Set rstRecords = .OpenRecordset
End With
So you can "stuff" in any sql you want for that one PT query - and use it throughout your application.

Run-time Error 2498 for Append and Make Table Queries Created in VBA

I'm getting a 2498 error and really don't understand why. I'm building a string in VBA and am getting the error with the following line of code...
DoCmd.OpenQuery qdfNew, acNormal
It happened with a very long string created to create the query so I simplified the code as much as possible and am still getting the error.
Here's the code...
Option Compare Database
Option Explicit
Dim dbsFootball As Database
Dim strInsertSQL, strSelectSQL, strIntoSQL, strFromSQL, strOrderSQL, strSQL As String
Dim qdfNew As QueryDef
Sub CreateFormattedData()
Set dbsFootball = CurrentDb()
strSelectSQL = ""
strIntoSQL = ""
strFromSQL = ""
strOrderSQL = ""
strSQL = ""
strSelectSQL = "SELECT [tbl_Raw_League_Data].[Season]"
strIntoSQL = "INTO [tbl_Manip Data]"
strFromSQL = "FROM [tbl_Raw_League_Data]" _
+ "LEFT JOIN Referees ON [tbl_Raw_League_Data].[Referee] = Referees.[Referee from Source Data]"
strSQL = strSelectSQL + " " + strIntoSQL + " " + strFromSQL + " " + strOrderSQL
On Error Resume Next ' If query doesn't exist, error won't stop execution
DoCmd.DeleteObject acQuery, "pgmqry_Create Table tbl_Manip"
On Error GoTo 0 ' Reset error handler
Set qdfNew = dbsFootball.CreateQueryDef("pgmqry_Create Table tbl_Manip", strSQL)
DoCmd.OpenQuery qdfNew, acNormal
End Sub
The source field, [tbl_Raw_League_Data].[Season], is a "Short Text" data type (field size = 7).
If I terminate the VBA code and run the query that was created by the code, it works fine with no apparent errors. However, it will never run the query from within the VBA code.
I was originally getting the error 2498 when using "INSERT INTO" for an append query, but realized that the table could as easily be recreated at code execution time.
I'm lost and would sure appreciate some ideas!
Thanks in advance,
Jason
You are passing the querydef object to DoCmd.OpenQuery when it expects a string referencing name of a stored query object. Consider using the querydef's Name property:
DoCmd.OpenQuery qdfNew.Name, acNormal
Alternatively, use .Execute command from database object using the SQL string variable, bypassing any need for querydef:
dbsFootball.Execute strSQL, dbFailOnError
Or with querydef object, as #HansUp suggests, where you simply execute directly since it is an action query:
qdfNew.Execute dbFailOnError
Do note above two options bring up the regular MS Access discussion, of using stored vs VBA string query. While the former is precompiled and runs through query optimizer caching best plan, the latter can have sql dynamically created (structural components that is like SELECT, FROM and JOIN clauses as both can use passed in parameters). From your code snippet consider saving SQL query beforehand without needing to build it in VBA on the fly, and call it with DoCmd.OpenQuery.

MS Access: Use variables instead of text.SetFocus method to query

I have two parameters form a FROM and THRU textbox. The code object is txtFROM and txtTHRU. Now I tried to open the query and reports with a txtFROM.SetFocus and txtTHRU.SetFocus and used in the query criteria: Between [FORMS]![ReportName]![txtFROM].[Text] and [FORMS]![ReportName]![txtTHRU].[Text]. However nothing turns up when I link a button to the query and report to show the data with those two parameters. I think it may be due to the fact that the .SetFocus method will only work on one parameter, so I think writing VBA variables to pass into a query might work if possible. The thing is I do not know if it is possible to call a VBA variable while running to a query as it were an object. The variables would otherwise read .SetFocus to ready the parameter to be passed to the Access query.
DoCmd.SetWarnings False
If IsNull(txtFROM.Value) = False And IsNull(txtTHRU.Value) = False Then
dataFROM = CDate(txtFROM.Value)
dataTHRU = CDate(txtTHRU.Value)
End If
DoCmd.OpenQuery ("Expiring")
DoCmd.OpenReport ("Expirees"), acViewPreview
DoCmd.SetWarnings True
The above variables dataFROM and dataTHRU would be what I would like to fit in the query criteria to reference the Form which displays reports.
You might need to script the query "on the fly" by using CreateQueryDef. Sort of like:
Dim db as Database
Dim qdf as QueryDef
Set db = CurrentDB
Set qdf = db.CreateQueryDef("Expiring", "SELECT * FROM MyTable WHERE " &_
"MyDate >= #" & CDate(txtFROM.Value) & "# and MyDate =< #" CDate(txtTHRU.Value) & "#")
DoCmd.OpenReport "Expirees", acViewPreview
Of course, you'll probably need to add some code at the beginning to delete that query if it already exists. Definitely inside an If/Then because if the code happens to burp and doesn't create the query one time, it'll crash the next time you run it.
Edit
As suggested by HansUp, another option is simply to alter the query's SQL statement, which you can do in code.
Set myquery = db.OpenQueryDef("Expiring")
strsql = "SELECT * FROM MyTable WHERE " &_
"MyDate >= #" & CDate(txtFROM.Value) & "# and MyDate =< #" CDate(txtTHRU.Value) & "#"
myquery.SQL = strsql
myquery.Close
It looks like there was a mixup in my query code, the FROM was duplicated, FROM FROM, not FROM THRU. The code works as it should have with the reference to the Reports and Form which the text controls. Keep with the usual method then.

How to run a SQL select statement in VB

I have been looking around but can't seem to find out how to do this.
I'm trying to execute a SELECT sql statement in VB that takes in a parameter from a form. For example the user selects a From and a To date and the SQL should take what they selected.
I know that you cannot use the DoCmd.Execute method for SELECT SQL so I would need to open the record set - but how? This is what I have tried so far
Dim recordSet As DAO.recordSet
Dim SQL As String
SQL = "SELECT * FROM tblWebMeetingData"
Set recordSet = CurrentDb.OpenRecordset(SQL)
'More code in here
recordSet.Close
Set recordSet = Nothing
Because this executes without an error I assume it's actually getting the results - so is there a way to see what it is actually returning?
Thanks
First: It's a good advice to rename the recordset to rs, for example, because "recordset" is a reserved name. This is misunderstandable.
This recordset contains the records you queried by your SQL statement. You may access those data by rs.fields("fieldname").value. Move to the next recordset with rs.movenext.
To incorporate the form's control value I use the way to build the full SQL statement prior to opening the recordset. Say the form is named "myform" and the control "mycontrol", you may write some kind of
SQL = "SELECT * FROM tblWebMeetingData WHERE myfield = " & forms!myform.mycontrol.value
Please be sure the form only contains valid values, because any wrong formatted value will directly lead to an SQL execution error.
I hope it was this, what you wanted.
Here you have come sample code about iterating trought RecordSet and using values from it( I hope it helps a bit):
Dim i As Integer
Do While Not rs.EOF
Sheets("D_" & day).Cells(i, 1) = rs.Fields(0).Value
Sheets("D_" & day).Cells(i, 2) = rs.Fields(1).Value
rs.MoveNext
i = i + 1
Loop
rs.Close

SQL Query to VBA and display result in Form

So I have a few Queries already written and my goal is to have a user input certain fields that would change the way the Query is returned, basically having the user change 2 or 3 parameters of the original Query.
First, I'm having problems getting a Query to execute in VBA:
Private Sub QResultButton_Click()
DoCmd.OpenQuery (Readings2009, acViewPreview,acReadOnly)
End Sub
[Readings2009 is a Query I created in Access] This returns a syntax error.
I have also see this done:
strSQL = "SELECT Readings2009.id, Readings2009.othercolumn, Readings2009.another
WHERE Readings2009.something > today() ..."
DoCmd.RunSQL (strSQL)
I can't get either to work. Any help would be greatly appreciated.
In this example, the name of the query must be a string, that is, it must be in quotes:
DoCmd.OpenQuery "Readings2009"
See: http://msdn.microsoft.com/en-us/library/aa220295(office.11).aspx
The other example is for running action queries,not for opening queries to view them.
It would be best to create a form and to use that to display your query.