Syntax error for SQL update statement in access - sql

I ran a SQL UPDATE statement in MS Access, but received a error message
Syntax error (missing operator) in query expression
I searched in internet, but any solutions works in my situation.
My code is:
Private Sub Command111_Click()
CurrentDb.Execute " UPDATE test3 " & _
"SET OrderStatus= 'Producing' " & _
"WHERE OrderID='" & Me!cboOrderID1 & "' ProductName='" & Me!ComboProduct1 & "'"
End Sub
Please help me check where is wrong.
Thanks

I am assuming that OrderID is int so it cannot be in '' quotes and must be as number in statement
"WHERE OrderID=" & Me!cboOrderID1 & " AND/OR ProductName='" & Me!ComboProduct1 & "'"
Also you forgot to use AND or OR

Forgot your AND
Private Sub Command111_Click()
CurrentDb.Execute " UPDATE test3 " & _
"SET OrderStatus= 'Producing' " & _
"WHERE OrderID='" & Me!cboOrderID1 & "' AND ProductName='" & Me!ComboProduct1 & "'"
End Sub

Thank you guys! This code works in my situation.
Private Sub Command111_Click()
CurrentDb.Execute " UPDATE test3 " & _
"SET OrderStatus= 'Producing' " & _
"WHERE OrderID='" & Me!cboOrderID1 & "' AND ProductName=" &CStr(Me!ComboProduct1) & ""
End Sub
In my case, the ProductName is sourced from a combo box.

Related

ms-access run-time error 3075 extra ) in vbasql

Code
strSQL = "SELECT tblHS_area_fields.hsaf_id " _
& "FROM tblHS_area_fields " _
& "WHERE (((tblHS_area_fields.hs_area_id)=" & hs_area_id & ") AND ((tblHS_area_fields.hsf_id)=13))"
Set rs = db.OpenRecordset(strSQL)
Errors
The error when trying to run from a Form is:
Extra ) in query expression '(((tblHS_area_fields.hs_area_id)=" &
> hs_area_id & ") AND ((tblHS_area_fields.hsf_id)=13))'
Getting an error from immediate window:
Compile error: expected: line number or label or statement or end of statement
All fields are numbers.
What is wrong with the VBA code and SQL statement?
Just remove all brackets in your sql:
strSQL = "SELECT tblHS_area_fields.hsaf_id " & _
"FROM tblHS_area_fields " & _
"WHERE tblHS_area_fields.hs_area_id = " & hs_area_id & " AND tblHS_area_fields.hsf_id = 13 "
In this case you don't need the brackets.
Not an answer, but too long for a comment:
Next time, add a Debug.Print strSql, then create a query in SQL view, copy you SQL statement from the debug window (ctrl+G) and paste you statement there.
Or just paste it in Visual Studio...
You should then quickly see the issue(s)
Consider to debug-print and log your SQL before executing: Debug.print(strSQL).
Opening brackets must match closing ones
Some break-down helps recognizing and matching, correct is:
strSQL = "SELECT hsaf_id" _
& " FROM tblHS_area_fields" _
& " WHERE (" _
& "( hs_area_id =" & hs_area_id & ")" _
& " AND ( hsf_id = 13 )" _
& ")"
For SQL templates you could also use string replace function or string-templating with a custom-function. See VBA string interpolation syntax.

Run-time error ‘3061’: Too few parameters expected 1

i had this error when i was trying to INSERT records to a local table with VBA.
I have checked the data type and putting in the quotes for the the short text data type but it doesn't work.
table_newid = "SELECT Cint(t1." & id_name(i) & "_new), " & Replace(select_column_str, local_table_name, "t2") & " FROM " & vbCrLf & _
"(SELECT CInt(DCount(""[" & id_name(i) & "]"", """ & qry_distinct_id_name & """, ""[" & id_name(i) & "]<="" & [" & id_name(i) & "])) as " & id_name(i) & "_new, * FROM " & qry_distinct_id_name & ") AS t1 " & vbCrLf & _
"LEFT JOIN " & local_table_name & "_ALL as t2 " & vbCrLf & _
"ON t1." & id_name(i) & " = t2." & id_name(i) & " " & vbCrLf & _
"WHERE t2.database = '" & database_name & "'"
strQuery = "INSERT INTO " & local_table_name & "_temp (" & temp_field(i) & ", " & Replace(select_column_str, local_table_name & ".", "") & ") " & vbCrLf & table_newid
Debug.Print strQuery
DoCmd.SetWarnings False
db.Execute strQuery
DoCmd.SetWarnings True
From the debug.print, i have got:
INSERT INTO TblLUMachineTypes_temp (MachTypeID_new, MachTypeID, MachTypeCode, MachTypeMod, MachTypeDesc, MachTypeDisc, NewCode, Approved, mttime, CreatedBy, CreatedTS, ModifiedBy, ModifiedTS)
SELECT t1.MachTypeID_new, t2.MachTypeID, t2.MachTypeCode, t2.MachTypeMod, t2.MachTypeDesc, t2.MachTypeDisc, t2.NewCode, t2.Approved, t2.mttime, t2.CreatedBy, t2.CreatedTS, t2.ModifiedBy, t2.ModifiedTS FROM
(SELECT CInt(DCount("[MachTypeID]", "qry_TblLUMachineTypes_id_distinct", "[MachTypeID]<=" & [MachTypeID])) as MachTypeID_new, * FROM qry_TblLUMachineTypes_id_distinct) AS t1
LEFT JOIN TblLUMachineTypes_ALL as t2
ON t1.MachTypeID = t2.MachTypeID
WHERE t2.database = 'CPM-252-2'
When i copied this query and execute it manually, it works fine but not with VBA. Any idea?
Thanks in advance.
Remove all the & vbCrLf from your code, they are not necessary and I assume they corrupt the SQL syntax.
I found the problem. I found that qry_distinct_id_name query table has a Dlookup function in there that returns a string value, which will work when executing the query manual but doesn't work when you run it with VBA. So I have re-written the code to put in the quote before and after dlookup() function.

How to fix "Run-time error '3464': Data type mismatch in criteria expression." in MS Access

I am working on a form on Access. It is supposed to insert data into a table, but I keep getting error 3464.
I am a little new to Visual Basic. This was previously working, but no longer. I am using SQL Server as a back-end. The connection works and it was inserting new rows. I have looked online but have not found a comprehensive explanation of this error.
Private Sub mSubmitButton_Click()
CurrentDb.Execute "INSERT INTO dbo_Reporting_Table([Date], Vendor, Ordered_By, Picked_Up_By, Reported_By) " & _
" VALUES('" & Me.mDate & "','" & Me.mVendor & "','" & Me.mOrdered_By & "','" & _
Me.mPicked_Up_By & "','" & Me.mReported_By & "')"
CurrentDb.Execute "INSERT INTO dbo_Items_Table([PO#], [Item], [Price], [Equipment], [Quantity]) " & _
" VALUES(" & Me.mPONumber & ",'" & Me.mItemInput0 & "'," & Me.mPriceInput0 & ",'" & _
Me.mEquipmentInput0 & "'," & Me.mQuantityInput0 & ")"
Me.mItemInput0 = ""
Me.mPriceInput0 = ""
Me.mEquipmentInput0 = ""
Me.mQuantityInput0 = ""
Me.mDate = ""
Me.mVendor = ""
Me.mOrdered_By = ""
Me.mPicked_Up_By = ""
Me.Requery
Exit Sub
Error_PopupMessage:
'Response = MsgBox(Message, vbOKOnly + vbInformation, "Form Entry Hint", "help", "1000")
Exit Sub
End Sub
Any advice on what I might be doing wrong would be greatly appreciated.
My problem was that, in the form, I was not entering all of the required fields before I pressed submit. I now have an if statement that ends the process if the required fields are null. Hope this might be of use to someone.
If Eval(IsNull(Me.mDate.Value) Or IsNull(Me.mVendor.Value) Or IsNull(Me.mPicked_Up_By.Value) Or IsNull(Me.mReported_By.Value)) Then
MsgBox " Make sure you have entered the Date, Vendor, Purchaser, and signed the form. "
Exit Sub
ElseIf Eval(IsNull(Me.mItemInput0.Value) Or IsNull(Me.mEquipmentInput0.Value) Or IsNull(Me.mPriceInput0.Value)) Then
MsgBox " Please enter atleast one complete row of an item for the PO. "
Exit Sub
Else
End If

Handling an external Access database within an Access Database with VBA?

So I'm a little confused as to how to handle an external database and current database within VBA code. Below is a sub whose purpose is to update the current Access database with unique entries found in the external Access database.
The external SourceDBPath and SelectedTable is passed in, and I specify the external database and table with the string variable SourceDBTable. Then, in the SQL, I try to pull out entries with values that don't match their coresponding field so only unique entries between the two DBs are inserted into the source database.
(For Example, where source = external:
NOT EXIST sourceDB.SelectedTable.Field1 = currentDB.SelectedTable.Field1 And sourceDB.SelectedTable.Field2 = currentDB.SelectedTable.Field2 And sourceDB.SelectedTable.Field3 = currentDB.SelectedTable.Field3, etc.)
SO, my questions are:
1) Do I need to specify the current database within the SQL (like currentDB.table.field), or will it default to the current database if a table or field is called without a prefix (just table or field, like in the code below)?
2) Ultimately, am I going about this in the right way?
My code:
Private Sub UpdateDatabaseTable(SourceDBPath As String, SelectedTable As String)
Dim SourceDBTable As String
On Error GoTo DBError
SourceDBTable = "[;DATABASE=" & SourceDBPath & "]." & SelectedTable
Call DoCmd.RunSQL("INSERT INTO " & SelectedTable & " " & _
"SELECT Field1, Field2, Field3 " & _
"FROM " & SourceDBTable & " " & _
"WHERE NOT EXISTS( SELECT * " & _
"FROM " & SourceDBTable & " " & _
"WHERE (Field1=" & SourceDBTable & ".Field1 And Field2=" & SourceDBTable & ".Field2 And Field3=" & SourceDBTable & ".Field3"));")
GoTo EndSub
DBError:
MsgBox "Database Error!" & vbCrLf & "Error #" & Str(Err.Number) & ": " & Err.Source & vbCrLf & Err.Description, vbExclamation, "Database Error"
EndSub:
End Sub
NOTE: I derived my SQL by extrapolating and modifying the code found in the solution HERE
You have 2 main mistakes in your code, otherwise, it should work.
Don't specify the tablename for each field. Use an alias instead
You want to escape both the tablename, and the database name, not only the database name
Private Sub UpdateDatabaseTable(SourceDBPath As String, SelectedTable As String)
Dim SourceDBTable As String
On Error GoTo DBError
SourceDBTable = "[;DATABASE=" & SourceDBPath & "].[" & SelectedTable & "]"
DoCmd.RunSQL "INSERT INTO " & SelectedTable & " t " & _
"SELECT Field1, Field2, Field3 " & _
"FROM " & SourceDBTable & " s" & _
"WHERE NOT EXISTS( SELECT * " & _
"FROM " & SourceDBTable & " s1 " & _
"WHERE (t.Field1=s1.Field1 And t.Field2=s1.Field2 And t.Field3=s1.Field3));"
GoTo EndSub
DBError:
MsgBox "Database Error!" & vbCrLf & "Error #" & Str(Err.Number) & ": " & Err.Source & vbCrLf & Err.Description, vbExclamation, "Database Error"
EndSub:
End Sub
I've also removed the deprecated Call keyword. Optionally, you can adjust this further by using CurrentDb.Execute, but that's not needed
Following code from my db SENDS data to OTHER db:
strExtract = gstrBasePath & "Program\Editing\ConstructionExtract.accdb"
CurrentDb.Execute "INSERT INTO Bituminous IN '" & strExtract & "' SELECT * FROM ConstructionBIT;"
gstrBasePath is a Global constant declared in a general module:
Global Const gstrBasePath = "\\servernamehere\Crm\Lab\Database\"
You can use literal string path within your procedure.
Following PULLS data from OTHER db:
CurrentDb.Execute "INSERT INTO Employees SELECT * FROM Employees IN '\\servername\filename.accdb'"

MS-Access VBA select query with multiple criteria

I have a dropdown box in an MS Access form which is populated by the following select query:
strSQL = "SELECT [Process] " _
& "FROM [dbo_tbl_Area_Process] " _
& "WHERE Area=" & Chr(34) & Me.Area_NC_Occurred & Chr(34) & ";"
Me.Process.RowSource = strSQL
I would like to add Active = -1 as a second criteria to the query to further limit the selections.
I have tried, so far unsuccessfully to add this second criteria and am at a loss as to how to proceed. Any help from the community would be most appreciated.
I have tried the following where conditions:
& "WHERE Area=" & Chr(34) & Me.Area_NC_Occurred & Chr(34) & " and Active =-1"
This does not return any results.
& "WHERE Area=" & Chr(34) & Me.Area_NC_Occurred & Chr(34) & " and Active ="-1""
This has a compile error:
Expected:end of statement
Following on from mintys comment regarding linked SQL server tables I changed the query to the following:
strSQL = "SELECT dbo_Tbl_Area_Process.Process " _
& "FROM dbo_Tbl_Area_Process " _
& "WHERE Area=" & Chr(34) & Me.Area_NC_Occurred & Chr(34) & " AND Active=True"
Adding the table references to the SELECT and FROM lines gives me the outputs I expected.
Thanks all for your comments