syntax error for update sql in access - sql

I got a syntax error when I ran a sql update in access 2013. The targeted table saves inventory balance data. to update the balance, the original data will subtract the consumption amount resulted from production activities. I use a query to get the sum of consumption. My codes are as follows:
Private Sub Command4_Click()
CurrentDb.Execute ("UPDATE tbl_Current_Stock As o" & _
“Inner join preview_Of_Raw_Material_Consumption As p” & _
“On o.Raw_Material =p.[Ingredient/Packaging material]” & _
"Set o.Stock_Level = o.Stock_Level- p.SumOfConsumption" )
End Sub
EDIT - Add current code that isn't working:
CurrentDb.Execute ("UPDATE tbl_Current_Stock As o Inner join preview_Of_Raw_Material_Consumption As p On o.[Raw_Material] = p.[Ingredient/Packaging material]Set o.[Stock_Level] = o.[Stock_Level]- p.SumOfConsumption from o p")

Your query looks something like this:
UPDATE tbl_Current_Stock As oInner join preview_Of_Raw_Material_Consumption As pOn o.Raw_Material =p.[Ingredient/Packaging material]Set o.Stock_Level = o.Stock_Level- p.SumOfConsumption
Can you spot the problem? Yes, you have run-on lines in the query. If you print the query string before running it, then the problem is obvious.
The solution is to put appropriate spaces in the string:
CurrentDb.Execute ("UPDATE tbl_Current_Stock As o" & _
" Inner join preview_Of_Raw_Material_Consumption As p” & _
" On o.Raw_Material = p.[Ingredient/Packaging material]” & _
" Set o.Stock_Level = o.Stock_Level- p.SumOfConsumption" )

Thank you Gordon. I finaly found the real problem of my code. I would like to share my experiences and it maybe helpful for others who are bothered by the same or similar problem. As I mentioned in my first question post, one of my update source comes from a query. this query is a sum of individual consumption and it is "unupdatable". By searching online I use a temporal table as the data source and the code runs smoothly.
CurrentDb.Execute ("Update tbl_Current_Stock As o Inner join tbl_Temp_Raw_Material_Consumption As s On o.Raw_Material = s.[Ingredient/Packaging material] Set o.Stock_Level = o.Stock_Level - s.Consumption")
Here tbl_Temp_Raw_Material_Consumption is the make table query of the original query.

Related

Optimize SQL query in VBA

I am trying to find the most optimized way to do this operation which runs an SQL statement in Access-VBA :
SQl = "UPDATE " _
& "MainTable As T1 " _
& "INNER JOIN TableOfLists As T2 " _
& "ON (T2.SecondList = T1.MultiValuedList.value) " _
& "Set [FOUND IN LISTS] = 'YES' "
DoCmd.RunSQL SQl
SQl = "UPDATE " _
& "MainTable As T1 " _
& "INNER JOIN TableOfLists As T2 " _
& "ON (T2.FirstList = T1.MultiValuedList.value) " _
& "Set [FOUND IN LISTS] = 'YES' "
DoCmd.RunSQL SQl
This code works, can be improved surely, but I didn't manage to find out how.
What I've tried so far and the results I got :
Adding 2 INNER JOIN but I get a syntax error 3075
Adding 2 conditions separated by an OR in the INNER JOIN condition but I get an error 3081 : can't join more than 1 table
This was my previous solution using 2 SELECT statements but I
got recommended to use JOIN instead
Any suggestions welcomed !
Here you go. This is kind of the ANSI SQL way of doing things, because joins within an UPDATE are not supported. (See this blog entry for more detail.) This is why you saw an error in your first approach (with two INNER JOINs, because Access/Jet is giving you a special feature in their UPDATE syntax, but it's not as fully-developed as vanilla SQL is. Your second approach (with an OR in the join condition) errors out because Access/Jet's support for conditions in join criteria is very limited (you wouldn't see this in Oracle or Postgres, for example). And it turns out your third approach (with two selects, but using IN instead of EXISTS) is the same, under the hood. So whoever told you to use joins was ill-informed :).
UPDATE MainTable SET [FOUND IN LISTS]='YES'
WHERE
EXISTS (SELECT 1 FROM TableOfLists WHERE FirstList=MainTable.[value])
OR
EXISTS (SELECT 1 FROM TableOfLists WHERE SecondList=MainTable.[value]);
Example in Access

Using SQL statement for conditional update tables in access 2013

I am new to databases. I am creating an Access database to track the inventory dynamics of our company. I have two tables. One is the current inventory stock, another is consumption raised by production activity. The update is done immediately after each production.
Before doing update, I want to verify the same unit is used in both stock status and consumption sheet. I try to do something like these:
Private Sub Command4_Click()
CurrentDb.Execute "SELECT o.Unit, s.Material_Unit" & _
"CASE WHEN o.Unite = s.Material_Unit" & _
"THEN UPDATE tbl_Current_Stock As o INNER JOIN bl_Temp_Raw_Material_Consumption AS s ON o.Raw_Material = s.[Ingredient/Packaging material] Set o.Stock_Level = o.Stock_Level - s.Consumption" & _
" Print'Congratulations! You have successfully updated inventory balance!'" & _
"ElSE PRINT ' Units of source data and targeted data are not matched!'" & _
"Exit Sub" & _
"End" & _
"FROM tbl_Current_Stock As o, bl_Temp_Raw_Material_Consumption AS s"
END sub
But it seems some errors exist. Please help me on these codes.
Thanks.
Your code is totally wrong. You can not use CASE to datermine which statement to execute, UPDATE or PRINT(PRINT is useless here, in MS Access).
You need to use either:
IF statement in your SQL query - declare o.Unite and s.Material_Unit as variables and compare them, if they match then execute update.
IF #unite = #materialunite
BEGIN
[Your Update Statement]
END
The other way:
Declare VB variables, assign the o.Unite and s.Material_Unit values to them, and write IF - ELSE statements in VB and execute your SQL queries.

run time error 3067 in Access with SQL query

All Works fine now! Thank you all for your help
I have been looking at the same line of code for the last two hours and don't understand why I continue to get the same Run Time Error 3067 message (input for the query must contain at least one table/query). This query is suppose to take three tables, linked with relationships and past 4 columns to a 4th table. The code below I copied directly from a query built in Access which worked..
DoCmd.SetWarnings False
st_sql = "INSERT INTO tblContactsProjectTrk01 ([Participant], [Sub_Project], [Role_type], [Completion_Percentage])" & _
"SELECT [tblProjManagementPhaseParticipants].[Participant], [tblProjectMasterList].[Sub project], [tblProjManagementPhaseParticipants].[Role_type], Avg([tblMasterListOfEvents].[Completion percentage]) AS MediaDiCompletion percentage" & _
"FROM[tblMasterListOfEvents] INNER JOIN ([tblProjManagementPhaseParticipants] INNER JOIN [tblProjectMasterList] ON [tblProjManagementPhaseParticipants].[ID_Project] = [tblProjectMasterList].[ID Project]) ON ([tblProjectMasterList].[ID Project] = [tblMasterListOfEvents].[ID Project]) AND ([tblMasterListOfEvents].[ID Event] = [tblProjManagementPhaseParticipants].[ID_Event])" & _
"GROUP BY([tblProjManagementPhaseParticipants].[Participant], [tblProjectMasterList].[Sub project], [tblProjManagementPhaseParticipants].[Role_type])" & _
"ORDER BY[tblProjManagementPhaseParticipants].[Participant]"
Application.DoCmd.RunSQL (st_sql)
There is no space before the FROM, so it is actually percentageFROM. I think it should be
...Avg([tblMasterListOfEvents].[Completion percentage]) AS [MediaDiCompletion percentage] " & _
"FROM[tblMasterListOfEvents]...
You have the same problem with your line wrapping before your GROUP BY and ORDER BY statements. You need spaces between the previous line and those two statements.

Join operation syntax error

I am trying to make a query through a button; though it says
Syntax error in JOIN operation. When I click it... I can't find the syntax error, maybe you guys can help me out? This is the code:
Set qdef = CurrentDb.CreateQueryDef("UnitMoreInfoQ", _
"SELECT UnitsT.*, WorkOrdersQ.CustomerName, WorkOrdersQ.ClientName, WorkOrdersQ.WorkOrderNumber " & _
"FROM UnitsT inner join workordersQ on WorkOrdersT.WorkOrerID=WorkOrdersQ.WorkOrderID " & _
"WHERE UnitsT.UnitID = " & txtWorkOrderID.Value)
The problem seems to be with your JOIN condition:
WorkOrdersT.WorkOrerID=WorkOrdersQ.WorkOrderID
There isn't a WorkOrdersT table or table alias defined in the FROM or other join, so your query isn't valid.
Make it easier on yourself to find and fix SQL errors.
Use a string variable to hold the SQL statement your code constructs. You can Debug.Print that statement before using it with CreateQueryDef. Then when troubleshooting, go to the Immediate window (Ctrl+g) to examine the statement your code is attempting to use. You can copy it from there and then paste it into SQL View of a new query for further testing. And if you need help, show us the completed statement text instead of the VBA code which builds the statement.
Dim strSelect As String
strSelect = "SELECT u.*, w.CustomerName, w.ClientName, w.WorkOrderNumber " & _
"FROM UnitsT As u inner join workordersQ AS w " & _
"on u.WorkOrerID=w.WorkOrderID " & _
"WHERE u.UnitID = " & txtWorkOrderID.Value
Debug.Print strSelect
Set qdef = CurrentDb.CreateQueryDef("UnitMoreInfoQ", strSelect)
Alternatively, use the query designer to create the query you need from scratch. Once you get that working, switch to SQL view, copy the statement text, and revise your VBA code to create the same statement.

SQL Access VBA UPDATE table with another table? Too Few Parameters

I am looking to update one of my tables with another table depending on a field condition. I am wondering what the correct way to do this is. I tried to do UPDATE statements with the 2 tables, but everytime it came out with this error: Too few Parameters, Expected 2
My goal:
If SOURCING field = O, I want Zip Code to be Origin Postal Code
If SOURCING field = D, I want Zip Code to be Dest Postal Code
So as of right now, I am simply doing a LEFT JOIN with a condition. Is this the best way to do it? Or should I have done this with the original INSERT statement somehow?
CurrentDb.Execute "UPDATE Processing" & _
" LEFT JOIN tblImport" & _
" ON Processing.[BATCH_NO] = tblImport.[BATCH_NO]" & _
" SET Processing.[Zip Code] = tblImport.[Origin Postal Code]" & _
" WHERE tblImport.[Sourcing] = O;"
CurrentDb.Execute "UPDATE Processing" & _
" LEFT JOIN tblImport" & _
" ON Processing.[BATCH_NO] = tblImport.[BATCH_NO]" & _
" SET Processing.[Zip Code] = tblImport.[Dest Postal Code]" & _
" WHERE tblImport.[Sourcing] = D;"
I have tried changing the WHERE statement since I am not sure if it should be in quotes, single quotes, not in quotes, etc... but I have come up empty there. Everything else looks correct to me.
Here's what I do, you might find this helpful; Set a variable equal to your SQL string, then CurrentDB.Execute the variable. Why is this helpful? Because you can break the code after the variable is set, and then copy the SQL into a new query and see what it's complaining about. :o)
Dim tmpUpdate as string
tmpUpdate = "UPDATE Processing" & _
" LEFT JOIN tblImport" & _
" ON Processing.[BATCH_NO] = tblImport.[BATCH_NO]" & _
" SET Processing.[Zip Code] = tblImport.[Origin Postal Code]" & _
" WHERE tblImport.[Sourcing] = O;"
CurrentDB.Execute tmpUpdate
Set a breakpoint on the "tmpUpdate =" line, and then run the code. When it hits the breakpoint, press F8 to step to the next line. In the Immediate window, type "?tmpUpdate" (without the quotes) and see what it thinks the variable is equal to. Then, go to the database, create a new query and go to the SQL of the query. Copy and paste the SQL from the Immediate window and try running the query. If it pukes, go to the Design view and see if you can see anything that doesn't look right.