Run SQL Update Query in MS Access VBA - sql

I am trying to run this code to fire an update query from VBA. Access is giving me a syntax error. I suspect this has to do with the fact that I'm trying to run an update query using an INNER JOIN with a form. Is what I'm trying to do at all possible?
Private Sub Btn_Edit_Data_Click()
Dim db As DAO.Database
Dim UpdateQdf As DAO.QueryDef
Dim UpdateSQL As String
Set db = CurrentDb()
Set UpdateQdf = db.QueryDefs("Qry_Update_Counterparty_Data")
UpdateSQL = "UPDATE Repository_Redux INNER JOIN [Forms]![Frm_Reject_Button] ON Repository_Redux.[Counterparty ID] = [Forms]![Frm_Reject_Button]![Txt_CP_ID] " & _
"SET Repository_Redux.[Counterparty Name] = [Forms]![Frm_Reject_Button]![Txt_CP_Name_Edit]"
UpdateQdf.SQL = UpdateSQL
DoCmd.OpenQuery "Qry_Update_Counterparty_Data"
Set db = Nothing
Set qdf = Nothing
End Sub
I solved it this way, thanks everyone:
UpdateSQL = "UPDATE Repository_Redux SET Repository_Redux.[Counterparty Name] = [Forms]![Frm_Reject_Button]![Txt_CP_Name_Edit] WHERE Repository_Redux.[Counterparty ID] = [Forms]![Frm_Reject_Button]![Txt_CP_ID]"

Just a suggestion, I've not tried this...
On your form you have have an event handler that stores in a global variable (yes, I know that's dodgy) the values from your form that you intend to use in the query. Then you can define a function that reads the global variable. Then you can use the function in the SQL query.
Let us know how you get on.
Googling suggests other have tried this
Global Variable as query parameter - PC Review
How to put global variable name in query
Anybody else got a better "global state machine" to bridge the form to the SQL?

No, you can never join a form in a query (or SELECT FROM a form, for that matter). You can only join in tables or other queries.
You can, however, try to join in a forms record source.

Related

access 2010 docmd.runSQL

I am using ACCESS 2010 and trying to run a simple command in one of my form buttons btnRemove_Click() and for some reason it always returns an error "Run-Time error '2342' A RunSQL action requires an argument consisting of an SQL statement"
my code is here...
Private Sub btnRemove_Click()
Dim srtSQL As String
StrSQL = "SELECT TblProduct.Product
, TblItem.Product_ID
, TblOrder.OrderID
FROM TblProduct
INNER JOIN (TblOrder
INNER JOIN TblItem
ON TblOrder.OrderID = TblItem.OrderID)
ON TblProduct.ProductID = TblItem.Product_ID
WHERE (((TblOrder.OrderID)=3));"
DoCmd.RunSQL StrSQL
Text62.SetFocus
Text62.Text = StrSQL
End Sub
the reason I want to run the DoCmd.RunSQL command as string is that later I will remove the (TblOrder.OrderID)=3 by a field in my form and I can see many people using this command normally in there videos in YouTube and tutorials, but seriously I have no idea why does not work.
Might be a bit late on this one. But the problem is DoCmd.RunSQL is for running Updates/Delete type SQL and not SELECT. You need to Open a Recordset to "use" the Data returned.

querydef doesnt work in exportxml

I have a query that i wan't to use in Application.ExportXML. But the query expects a parameter, this parameter has to be a value of textbox in my form. Right now i have something like this.
sql = "SELECT * FROM Reports WHERE Reports.Ref_Q ='" & txtRef & "';"
Set qd = CurrentDb.QueryDefs("getReports")
qd.sql = sql
Application.ExportXML acExportQuery, getReports, strPath
When I run this code i get the following error:
The command or action '|' isn't avaible now
I als tried doing it like this
Set qd = CurrentDb.QueryDefs("getReports")
qd.Parameters("prm") = txtRef.Value
But then the prompt screen for the parameter keeps comming on the screen.
Set qd = CurrentDb.QueryDefs("getReports") is expecting to find a saved query called getReports, which may not exist.
You would need something like:
sql = "SELECT * FROM Reports WHERE Reports.Ref_Q ='" & txtRef & "';"
Set qd = CurrentDb.CreateQueryDef("getReports", sql)
DB.QueryDefs.Refresh
Application.ExportXML acExportQuery, getReports, strPath
Or:
sql = "SELECT * FROM Reports WHERE Reports.Ref_Q = [prm];"
Set qd = CurrentDb.CreateQueryDef("getReports", sql)
qd.Parameters("[prm]") = txtRef.Value
DB.QueryDefs.Refresh
Application.ExportXML acExportQuery, getReports, strPath
DB.QueryDefs.Refresh is usually necessary, as without it, Access won't find your newly created query.
Using parameters is preferable when you need to reuse the query lots of times with different parameters, as creating a query has more overhead than just calling it with a different parameter.
You might want to add a DB.QueryDefs.Delete "getReports" if you don't want your query hanging around.

Is it possible to pass parameters programmatically in a Microsoft Access update query?

I have a query that's rather large, joining over a dozen tables, and I want to pull back records based on an id field (e.g.: between nStartID and nEndID).
I created two parameters and tested them as criteria and they work fine.
The issue is, I need to run an insert query from this main query, and need the parameters where they are, in the main query. So, I need to pass parameters to it programmatically.
Anyone have a clue as to how this can be done?
Thanks.
I just tested this and it works in Access 2010.
Say you have a SELECT query with parameters:
PARAMETERS startID Long, endID Long;
SELECT Members.*
FROM Members
WHERE (((Members.memberID) Between [startID] And [endID]));
You run that query interactively and it prompts you for [startID] and [endID]. That works, so you save that query as [MemberSubset].
Now you create an UPDATE query based on that query:
UPDATE Members SET Members.age = [age]+1
WHERE (((Members.memberID) In (SELECT memberID FROM [MemberSubset])));
You run that query interactively and again you are prompted for [startID] and [endID] and it works well, so you save it as [MemberSubsetUpdate].
You can run [MemberSubsetUpdate] from VBA code by specifying [startID] and [endID] values as parameters to [MemberSubsetUpdate], even though they are actually parameters of [MemberSubset]. Those parameter values "trickle down" to where they are needed, and the query does work without human intervention:
Sub paramTest()
Dim qdf As DAO.QueryDef
Set qdf = CurrentDb.QueryDefs("MemberSubsetUpdate")
qdf!startID = 1 ' specify
qdf!endID = 2 ' parameters
qdf.Execute
Set qdf = Nothing
End Sub
Try using the QueryDefs. Create the query with parameters. Then use something like this:
Dim dbs As DAO.Database
Dim qdf As DAO.QueryDef
Set dbs = CurrentDb
Set qdf = dbs.QueryDefs("Your Query Name")
qdf.Parameters("Parameter 1").Value = "Parameter Value"
qdf.Parameters("Parameter 2").Value = "Parameter Value"
qdf.Execute
qdf.Close
Set qdf = Nothing
Set dbs = Nothing
Many thanks for the information about using the QueryDefs collection! I have been wondering about this for a while.
I did it a different way, without using VBA, by using a table containing the query parameters.
E.g:
SELECT a_table.a_field
FROM QueryParameters, a_table
WHERE a_table.a_field BETWEEN QueryParameters.a_field_min
AND QueryParameters.a_field_max
Where QueryParameters is a table with two fields, a_field_min and a_field_max
It can even be used with GROUP BY, if you include the query parameter fields in the GROUP BY clause, and the FIRST operator on the parameter fields in the HAVING clause.
You can also use TempVars - note '!' syntax is essential
Plenty of responses already, but you can use this:
Sub runQry(qDefName)
Dim db As DAO.Database, qd As QueryDef, par As Parameter
Set db = CurrentDb
Set qd = db.QueryDefs(qDefName)
On Error Resume Next
For Each par In qd.Parameters
Err.Clear
par.Value = Eval(par.Name) 'try evaluating param
If Err.Number <> 0 Then 'failed ?
par.Value = InputBox(par.Name) 'ask for value
End If
Next par
On Error GoTo 0
qd.Execute dbFailOnError
End Sub
Sub runQry_test()
runQry "test" 'qryDef name
End Sub

Invoking a SQL Procedure in the database via VBA code

I have an SQL query which takes up a parameter stored in the db. I want to invoke the same from VBA code which is running on the same db. I am using MS Access for my work.
So for example consider, I have an SQL query 'Q' which takes a parameter 'p', I intend to invoke this SQL query from my VBA code 'C' , which also naturally involves passing this parameter 'p' to the query.
Help much appreciated
Soham
There are a few possibilities here.
Let us say it is a SELECT query built on a form that holds the parameters to be used and that the input is safe:
s = "SELECT * FROM MyTable WHERE AText ='" & Me.MyText & "'"
This can be used like so:
Forms!SomeForm.RecordSource = s
Or
Set qdf = CurrentDb.CreateQueryDef("NewQuery", s)
However, the above can be done in other, better ways.
Let us say it is a ACTION query run from a form that holds the parameters to be used and that the input is safe:
s = "UPDATE MyTable Set AText ='" & Me.MyText & "'"
Then
Set db = CurrentDB
db.Execute s, dbFailOnError
Or you can use a temporary query, which can be safer:
'Temporary query
s = "UPDATE MyTable Set AText = MyRext"
Set qdf = db.CreateQueryDef("", s)
qdf.Parameters!MyText = Me.MyText
qdf.ReturnsRecords = False
qdf.Execute dbFailOnError
Something similar to the above would also be suitable for an existing query.
You can also pass the parameter to a procedure, in which case Me.MyText becomes a variable, or you can use Inputbox, which is rarely a good idea.
After that, there is the whole world of ADO.

error 3075 when running SQL in access 2007 vba

I wonder why I can't execute this SQL query in access 2007 through VBA, which can be executed when i create a query myself:
Private Sub SQL_Click()
Dim curDatabase As Database
Dim RS_REPORT As Recordset
Set curDatabase = CurrentDb
Set RS_REPORT = _
curDatabase.OpenRecordset("REPORT_CONTENT_ARCHIVE", dbOpenDynaset)
strStatement = "SELECT REPORT_CATEGORY1.DESCRIPTION, REPORT_CATEGORY2.DESCRIPTION, REPORT_CATEGORY3.DESCRIPTION, REPORT_RECOMMENDATION.RECOMMENDATION, REPORT_CONTENT_ARCHIVE.REPORT_UID, REPORT_CONTENT_ARCHIVE.CATEGORY1_ID, REPORT_CONTENT_ARCHIVE.CATEGORY2_ID, REPORT_CONTENT_ARCHIVE.CATEGORY3_ID" & _
"FROM (REPORT_CATEGORY1 RIGHT JOIN REPORT_CATEGORY2 ON REPORT_CATEGORY1.CATEGORY1_ID=REPORT_CATEGORY2.CATEGORY1_ID) RIGHT JOIN (REPORT_CATEGORY3 RIGHT JOIN (REPORT_CONTENT_ARCHIVE INNER JOIN REPORT_RECOMMENDATION ON (REPORT_CONTENT_ARCHIVE.CATEGORY3_ID=REPORT_RECOMMENDATION.CATEGORY3_ID) AND (REPORT_CONTENT_ARCHIVE.CATEGORY2_ID=REPORT_RECOMMENDATION.CATEGORY2_ID) AND (REPORT_CONTENT_ARCHIVE.CATEGORY1_ID=REPORT_RECOMMENDATION.CATEGORY1_ID)) ON (REPORT_CATEGORY3.CATEGORY2_ID=REPORT_RECOMMENDATION.CATEGORY2_ID) AND (REPORT_CATEGORY3.CATEGORY1_ID=REPORT_RECOMMENDATION.CATEGORY1_ID) AND (REPORT_CATEGORY3.CATEGORY3_ID=REPORT_RECOMMENDATION.CATEGORY3_ID)) ON (REPORT_CATEGORY2.CATEGORY2_ID=REPORT_CATEGORY3.CATEGORY2_ID) AND (REPORT_CATEGORY2.CATEGORY1_ID=REPORT_CATEGORY3.CATEGORY1_ID)" & _
"WHERE (((REPORT_CONTENT_ARCHIVE.REPORT_UID)=12));"
Set qryMRSA = curDatabase.CreateQueryDef("DATABASE_RECOMMENDATION_1", strStatement)
End Sub
I receive error of 3075, what is it?
Thanks!
This may be something obvious, but if your SQL string is writen in your code exactly as you write it here, you need an aditional space before FROM and WHERE.
Another way to find out what is going on is to print the SQL string, using Debug.Print strStatement, and copying it to a new blank query object, and see if it works.
Hope this is helpful