query syntax error... - sql

I have the following coding for a button. My problem is that the Query "SQLStory" is comming up with an error that it is missing a semi colon.
The combobox contains the item name and is ordered by the product ID and the SQLStory is supposed to move all items from the TblTotalSale to the table TblSaleStore. Any Ideas where the error is?
Private Sub StockOK_Click()
Dim SQLDelete1 As String
Dim SQLDelete2 As String
Dim SQLUpdate As String
Dim SQLStory As String
SQLDelete1 = "DELETE * FROM TblStock WHERE TblStock.ProductID = " & CboStockItem.Value
SQLDelete2 = "DELETE * FROM TblTotalSale WHERE TblTotalSale.ProductID = " & CboStockItem.Value
SQLUpdate = "INSERT INTO TblStock (ProductID, StockLevel) VALUES ( " & Me.CboStockItem.Value & "," & Me.TxtStockValue & " )"
SQLStory = "INSERT INTO TblSaleStore (ProductID) VALUES (TblTotalSale.ProductID) FROM TblTotalSale WHERE TblTotalSale.ProductID = " & Me.CboStockItem.Value
If IsNull(Me.TxtStockValue) Then MsgBox "Please Select An Item To Update Stock And Ensure A Value Has Been Entered" Else:
DoCmd.RunSQL SQLDelete1
DoCmd.SetWarnings False
DoCmd.RunSQL SQLStory
DoCmd.RunSQL SQLDelete2
DoCmd.RunSQL SQLUpdate
DoCmd.SetWarnings True
End Sub
Another problem I am having with this code is that the block of doCmd was happening whether the txt box TxtStockValue was null or not, and I only want them to happen if the box is not null... Any Ideas on that part either?
Thanks
Sam

Values are for just that, values such as 'abc' or 123, you need SELECT:
SQLStory = "INSERT INTO TblSaleStore (ProductID) " _
& "SELECT (TblTotalSale.ProductID) FROM " _
& "TblTotalSale WHERE TblTotalSale.ProductID = " _
& Me.CboStockItem.Value
But the above is odd, because you already have the ID in the combo, so, as I said in your previous post on the topic:
SQLStory = "INSERT INTO TblSaleStore (ProductID) " _
& "VALUES ( " & Me.CboStockItem.Value & " )"
Also, it was suggested to you that you should use debug.print when using SQL, this would allow you to view the SQL and paste it into the query design window to see if it worked. The debug.print line can be commented out when everything is working. When you are unfamiliar with SQL, there is a lot to be said for using the query design window to build your queries. You can then cut the SQL from SQL View and add quotes etc.
EDIT re Question Part 2
Dim db As Database
Set db = CurrentDB
If IsNull(Me.TxtStockValue) Then
MsgBox "Please Select An Item To Update Stock " _
& "And Ensure A Value Has Been Entered"
Else
db.Execute SQLDelete1, dbFailOnError
''DoCmd.SetWarnings False
db.Execute SQLStory, dbFailOnError
db.Execute SQLDelete2, dbFailOnError
db.Execute SQLUpdate, dbFailOnError
''DoCmd.SetWarnings True
End If

Related

How to find a syntax error in my SQL code?

I am trying to compile my code but I get the same error every time:
Syntax error (missing operator ) in query expression
' True Status.Subsystem Not LIKE '''
This is my code :
Sub Import_Loop_Check_list()
Dim strSQL As String
Dim SS_sel As String
Dim rcrd As DAO.Recordset
If IsNull(Cobsubsystem) Then
SS_sel = "True"
Else
If IsNull(Logic1) Then
SS_sel = "Status.Subsystem LIKE '" & Cobsubsystem & "' "
Else
SS_sel = "Status.Subsystem NOT LIKE '" & Cobsubsystem & "' "
End If
End If
strSQL = " SELECT DISTINCT LOOP_JB.Loop_name, [Easyplant Dump query].Subsystem, LOOP_JB.PANEL_FROM, LOOP_JB.ITR_PANEL_FROM, LOOP_JB.ITR_PANEL_FROM_state, LOOP_JB.CABLE_NUM, LOOP_JB.ITR_cable, LOOP_JB.ITR_STATE_Cable, LOOP_JB.Cabinet_JB, LOOP_JB.ITR_Cabinet_JB, LOOP_JB.ITR_STATE_CABINET, Multicors.CABLE_NUM AS Multicore, Multicors.ITR_PANEL_FROM, Multicors.ITR_PANEL_FROM_state, [Cabinet query].PANEL_TO, [Cabinet query].ITR_PANEL_TO, [Cabinet query].ITR_PANEL_TO_state INTO [LOOP_Check] " & _
" FROM (LOOP_JB INNER JOIN ([Cabinet query] RIGHT JOIN Multicors ON [Cabinet query].CABLE_NUM = Multicors.CABLE_NUM) ON LOOP_JB.Loop_name = Multicors.Loop_name) INNER JOIN [Easyplant Dump query] ON LOOP_JB.Loop_name = [Easyplant Dump query].Clean_Tag_Number" & _
" WHERE True " & SS_sel & strSQL
DoCmd.SetWarnings False
DoCmd.RunSQL strSQL
DoCmd.SetWarnings True
DoCmd.OpenTable "LOOP_Check"
End Sub
I looked at this again -- something else does not make sense.
You reference Status.Subsystem in the WHERE but there is no table named Status -- Did you not include the full query?
original answer
I think the error message is clear -- you have a strange where statement
WHERE True Status.Subsystem Not LIKE
you probably mean
WHERE Status.Subsystem Not LIKE
so change this line
" WHERE True " & SS_sel & strSQL
to this
" WHERE " & SS_sel & strSQL
Also, it does not right to me -- are you sure you want to do a RIGHT join to Multicors and not a left join? You want a row in your result for every row in the multicors table?

INSERT INTO - errors, but allows input into table

For reasons I cannot see I get the following error message:
Compile error: Method or data member not found
when I use the following:
Private Sub cmd_Add_Click()
Dim strSQL As String
strSQL = " INSERT INTO BERTHAGE " _
& "(BOAT, LOCATION, BERTH_WEEK, BERTH_YEAR, BERTHED) VALUES " _
& Me.Add_Boat & "','" _
& Me.LOCATION & "','" _
& Me.txt_week & "','" _
& Me.txt_year & "','" _
& Me.In_Port & "');"
cmd_Clear_Click
End Sub
Once I click OK and use the refresh button the entry is put into the database, but each time I do an entry I have to go to the same process.
I would like to figure out what method or data is missing?
I should add that there is an outnumber primary key field on this table (Berth_ID), and each time I use the cmd_Add button a new ID number is created for the new record. This includes creating a new ID number for the new record that triggers the error.
Here is all the VBA associated with this form
Private Sub Form_Load()
DoCmd.RunCommand acCmdRecordsGoToLast
End Sub
Private Sub LOCATION_Change()
Me.txt_Cur_Flo = Me.LOCATION.Column(1)
Me.txt_Cur_Doc = Me.LOCATION.Column(2)
Me.txt_Cur_Ori = Me.LOCATION.Column(3)
End Sub
Private Sub cmd_Add_Click()
Dim strSQL As String
strSQL = " INSERT INTO BERTHAGE " _
& "(BOAT, LOCATION, BERTH_WEEK, BERTH_YEAR, BERTHED) VALUES " _
& Me.Add_Boat & "','" _
& Me.LOCATION & "','" _
& Me.txt_week & "','" _
& Me.txt_year & "','" _
& Me.In_Port & "');"
cmd_Clear_Click
End Sub
Private Sub cmd_Clear_Click()
Me.Add_Boat = ""
Me.LOCATION = ""
Me.txt_Cur_Flo = ""
Me.txt_Cur_Doc = ""
Me.txt_Cur_Ori = ""
Me.Add_Boat.SetFocus
End Sub
Private Sub cmd_Close_Click()
DoCmd.Close
End Sub
Consider the best practice of parameterization and not string concatenation of SQL mixed with VBA variables. Due to missing quotes, the compiler attempts to reference a column name and not its literal value. Instead, consider parameterization with defined types which is supported with Access SQL using QueryDefs. Notice below, SQL and VBA are complete separate.
SQL (save as stored query)
PARAMETERS prmBoat TEXT, prmLoc INT, prmBerthed INT;
INSERT INTO BERTHAGE (BOAT, LOCATION, BERTHED)
VALUES(prmBoat, prmLoc, prmBerthed)
VBA
Dim db As Database
Dim qdef As QueryDef
Dim strSQL As String
Set db = CurrentDb
Set qdef = db.QueryDefs("mySavedParamQuery")
' BIND PARAM VALUES
qdef!prmBoat = Me.Add_Boat
qdef!prmLoc = Me.LOCATION
qdef!prmBerthed = Me.In_Port
' EXECUTE ACTION QUERY
qdef.Execute
Set qdef = Nothing
Set db = Nothing
Even better, save your query with form controls intact and simply call OpenQuery:
SQL (save as stored query)
INSERT INTO BERTHAGE(BOAT, LOCATION, BERTHED)
VALUES(Forms!myForm!Add_Boat, Forms!myForm!LOCATION, Forms!myForm!In_Port)
VBA
Private Sub cmd_Add_Click()
Dim strSQL As String
DoCmd.SetWarnings False ' TURN OFF APPEND PROMPTS
DoCmd.OpenQuery "mySavedActionQuery"
DoCmd.SetWarnings True ' RESET WARNINGS
Call cmd_Clear_Click
End Sub
Missing opening parenthesis after VALUES. Also missing apostrophe in front of Me.Add_Boat. These special characters must always be in pairs, an even number by counting.
If Berth_Week and Berth_Year are number fields (and should be), don't use apostrophe delimiters.
If In_Port is a Yes/No field, don't use apostrophe delimiters.
The issue appears to be that I was doubling up the inputs into the 'week' and 'year' field. this was happening (I believe) because those text box fields were already accessing the week and year information directly from the default value on the BERTHAGE table. Essentially I went through each input and would run it individually waiting for the error to occur. Once it occurred I took it out of the INSERT INFO statement. With the removal of week and year, everything is working. That was a painful exercise, and still not complete, but I am back to a function form/DB so I'll take the small victories when they occur.
Private Sub cmd_Add_Click()
Dim strSQL As String
CurrentDb.Execute " INSERT INTO BERTHAGE " & "(BOAT, LOCATION, BERTHED) VALUES ('" & Me.Add_Boat & "'," _
& Me.New_Loc & "," _
& Me.In_Port & ");"
cmd_Clear_Click
DoCmd.Requery
End Sub`

OpenRecordset not returning usable recordset / .edit not working?

Working on a database on Access, trying to run a query to find a record with the latest date and a 'where' condition.
Error returned is "Run Timer Error '3027' Cannot update. Database or object is read-only"
Following conditions:
Button is clicked on a form that contains a text field for 'fCheckInFor'.
Database 'ToolTests' fields
"CheckOut" is dates in format of "3/15/2019 5:35:31 PM"
"CheckIn" is dates in format of "3/15/2019 5:35:31 PM"
"CheckInFor" is a text field
"ToolNumber" is a text field
Public CheckInTool as String
Private Sub CheckIn_Click()
CheckInTool = "000"
If Me.fCheckInFor = "" Then
MsgBox "Enter Returning User."
Else
Dim dbsUE As DAO.Database
Dim rstUE As DAO.Recordset
Set dbsUE = CurrentDb
Set rstUE = dbsUE.OpenRecordset("SELECT Max([CheckOut]) FROM [ToolTests] WHERE [ToolNumber]= '" & CheckInTool & "'")
With rstUE
.Edit 'error occurs here
!CheckIn = Now()
!CheckInFor = Me.fCheckInFor
.Update
End With
MsgBox "Checked In"
DoCmd.Close acForm, "CheckIn"
End If
End Sub
So the error throws at the .Edit line, I'm unsure where to go from here. would also be fine with tossing the whole thing and going at it from a different direction.
If I get you right, you want to update a record that has a specific ToolNumber. So, if you want to use a subquery, you will either need to use that criterion in both the main query and the subquery, or link the subquery with the main query using that field:
Set rstUE = dbsUE.OpenRecordset( _ &
"SELECT CheckIn, CheckinFor FROM ToolTests WHERE" & _
" CheckOut IN (SELECT Max(CheckOut) FROM ToolTests AS tmp WHERE ToolNumber = ToolTests.ToolNumber)" & _
" And ToolNumber = '" & CheckInTool & "'")
Alternatively, you could simply sort the records in the correct order and update the first one:
Set rstUE = dbsUE.OpenRecordset( _ &
"SELECT CheckIn, CheckinFor FROM ToolTests WHERE" & _
" ToolNumber = '" & CheckInTool & "'" & _
" ORDER BY CheckOut DESC")

Access VBA: Number of query values and destination fields are not the same

I am trying to add data from an Access form to a table. When I ran sql code, I got an error message saying "number of query values and destination fields are not the same."
this is my code:
Private Sub CmdAddtoProductionDetails_Click()
Dim StrSql As String
StrSql = "Insert Into test1 (ProductName, [Lot Number], ProductionDate, Quantity, Unit, Client) Values(me! ComboProduct1, me! LotNoProduct1, me! txtDate, me! Product1Quantity! me!ComboProduct1Unit, me! ComboProduct1Client)"
CurrentDb.Execute (StrSql)
End Sub
A simpler and more direct method is to use a recordset:
Private Sub CmdAddtoProductionDetails_Click()
Dim rs As DAO.Recordset
Set rs = CurrentDb.OpenRecordset("Select Top 1 * From test1")
rs.AddNew
rs!ProductName.Value = Me!ComboProduct1.Value
rs![Lot Number].Value = Me!LotNoProduct1.Value
rs!ProductionDate.Value = Me!txtDate.Value
rs!Quantity.Value = Me!Product1Quantity.Value
rs!Unit.Value = Me!ComboProduct1Unit.Value
rs!Client.Value = Me!ComboProduct1Client.Value
rs.Update
rs.Close
Set rs = Nothing
End Sub
Your SQL string will be passed to the SQL engine which does not know how to interpret me!ComboProduct1 etc. You need to insert the values of those variables into the string:
Private Sub CmdAddtoProductionDetails_Click()
Dim StrSql As String StrSql = "Insert Into test1 (ProductName, [Lot Number], ProductionDate, Quantity, Unit, Client)" & _
" Values( '" & me! ComboProduct1 & "', '" & me! LotNoProduct1 & "', #" & Format(me! txtDate, "yyyy/mm/dd") & "#, " & CStr(me! Product1Quantity) & ", '" & me!ComboProduct1Unit & "', '" & me! ComboProduct1Client & "' )"
CurrentDb.Execute (StrSql)
End Sub
Put single quotes around strings but not around numbers. Some of your fields I wasn't sure if they were numbers or strings - I made a guess.
You need to be careful with dates - check that the SQL engine is interpreting dates in yyyy/mm/dd format correctly. It will convert the string #2016/06/04# to a date automatically for you.

Run Time error 3061 Too Few parameters. Expected 6. Unable to update table from listbox

All,
I am running the below SQL and I keep getting error 3061. Thank you all for the wonderful help! I've been trying to teach myself and I am 10 days in and oh my I am in for a treat!
Private Sub b_Update_Click()
Dim db As DAO.Database
Set db = CurrentDb
strSQL = "UPDATE Main" _
& " SET t_Name = Me.txt_Name, t_Date = Me.txt_Date, t_ContactID = Me.txt_Contact, t_Score = Me.txt_Score, t_Comments = Me.txt_Comments" _
& " WHERE RecordID = Me.lbl_RecordID.Caption"
CurrentDb.Execute strSQL
I am not sure but, you can try somethink like that
if you knom the new value to insert in the database try with a syntax like this one
UPDATE table
SET Users.name = 'NewName',
Users.address = 'MyNewAdresse'
WHERE Users.id_User = 10;
Now, if you want to use a form (php)
You have to use this
if(isset($_REQUEST["id_user" ])) {$id_user = $_REQUEST["id_user" ];}
else {$id_user = "" ;}
if(isset($_REQUEST["name" ])) {$name= $_REQUEST["name" ];}
else {$name = "" ;}
if(isset($_REQUEST["address" ])) {$address= $_REQUEST["adress" ];}
else {$adress= "" ;}
if you use mysql
UPDATE table
SET Users.name = '$name',
Users.address = '$adress'
WHERE Users.id_User = 10;
i don't know VBA but I will try to help you
Going on from my comment, you first need to declare strSQL as a string variable.
Where your error expects 6 values and access doesn't know what they are. This is because form objects need to be outside the quotations of the SQL query, otherwise (as in this case) it will think they are variables and obviously undefined. The 6 expected are the 5 form fields plus 'strSQL'.
Private Sub b_Update_Click()
Dim db As DAO.Database
dim strSQL as string
Set db = CurrentDb
strSQL = "UPDATE Main" & _
" SET t_Name = '" & Me.txt_Name & "'," & _
" t_Date =#" & Me.txt_Date & "#," & _
" t_ContactID =" & Me.txt_Contact & "," & _
" t_Score =" & Me.txt_Score & "," & _
" t_Comments = '" & Me.txt_Comments & "'," & _
" WHERE RecordID = '" & Me.lbl_RecordID.Caption & "';"
CurrentDb.Execute strSQL
end sub
Note how I have used double quotes to put the form fields outside of the query string so access knows they aren't variables.
If your field is a string, it needs encapsulating in single quotes like so 'string'. If you have a date field it needs encapsulating in number signs like so #date# and numbers/integers don't need encapsulating.
Look at the code I have done and you can see I have used these single quotes and number signs to encapsulate certain fields. I guessed based on the names of the fields like ID's as numbers. I may have got some wrong so alter where applicable... Or comment and I will correct my answer.