I have a subroutine in excel that I would like to write data to an Access table. I am trying to update a row in the table if it already exists, add it if it does not. Going off of the suggestion given on this MSDN blog by Jeremiah Clark, I have my query that I will execute from my Excel’s VBA subroutine:
UPDATE tblName
SET [Column1] = 'text', ...(other values)... [ColumnN] = 1234
WHERE ([Column1] = 'text' AND [Column2] = 'text2')
If @@ROWCOUNT = 0
INSERT INTO tblName
VALUES ( [Column1] = 'text', ...(other values)... [ColumnN] = 1234 )
The error it gives me is:
Syntax error (missing operator) in query expression '([Column1] = 'text' AND [Column2] = 'text2')
If @@ROWCOUNT = 0
INSERT INTO tblName
VALUES ( [Column1] = 'text', ...(other values)...'.
I’m pretty new to SQL, but have tried various ways of bracketing (parentheses-ing) the IF line in case the evaluation order was not what I expected, but that was to no avail. Is the first part of the query not being evaluated and thus @@ROWCOUNT cannot be executed properly?
Edit1: Using Access 2003 if that matters.
Solution:
Based on bluefeet’s suggestion (see his entire response):
objDB.Execute sqlStrSelect
recordset.Source = sqlStrSelect
recordset.Open , , adOpenDynamic, adLockOptimistic
If recordset.Fields(0) = 0 Then
objDB.Execute sqlStrInsert
Else
objDB.Execute sqlStrUpdate
End If
This relies on a modified SELECT query to get Access to return the Count of the records:
sqlStrSelect = "SELECT Count(id) FROM table1 WHERE id = 3"
HansUp correctly surmised that I was using an ADO connection, so executing the code had to be done differently from what bluefeet originally suggested.
The
@@ROWCOUNTis used for SQL Server not Access but since you are usingVBAyou could do something similar to this. Basically create your SQL statements as strings putting in your values that you are checking for. Then run query against the table first to see if the record exists, if it does then do theUPDATEif not then do theINSERT. I quickly tested this in MS Access 2003 and it works.EDIT: As HansUp pointed out you are querying from Excel, your code could be similar to this:
This has been tested from Excel 2003 to Access 2003 and worked. You need to have the references added to your Excel file for the Microsoft ActiveX Data Objects.