If not exists query results in "error in your SQL syntax" - sql

I would like to insert a row with SQL (in Visual Basic) and receive something like: "Error: You have an errin in your SQL syntax near IF NOT EXISTS ... at line 1"
Code looks like:
...
Try
query = "IF NOT EXISTS (Select Movie_Name from MovieDB where Movie_Name=" & placeholder & ") INSERT INTO MovieDB (Movie_Name) VALUES ('" & placeholder & "')"
'PREPARE CONNECTION
MySQLCmd = New MySqlCommand(query, dbConnection)
'OPEN DB
dbConnection.Open()
'EXECUTE QUERY
MySQLCmd.ExecuteNonQuery()
'CLOSE DB
dbConnection.Close()
Catch ex As Exception
...
I really dont get it anymore. Some ideas?

At a minimum you need single quotes around the first string as well:
--V --V
query = "IF NOT EXISTS (Select Movie_Name from MovieDB where Movie_Name='" & placeholder & "'); INSERT INTO MovieDB (Movie_Name) VALUES ('" & placeholder & "')"
As #Cameron astutely noticed, you also need a semicolon between the EXISTS function and the INSERT command
But you should look into using parameters instead of concatenating SQL - not only does it remove the need to delimit strings, but it prevents SQL injection and avoids syntax error if the string contains an apostrophe.

As far as I know "IF NOT EXISTS INSERT" is no valid MySQL syntax. This should work:
query = "INSERT INTO MovieDB (Movie_Name) VALUES ('" & placeholder & "') ON DUPLICATE KEY UPDATE Movie_Name = Movie_Name";
This tries to insert the new movie name and if this fails it does virtually nothing. (For this to work there must be a unique index on Movie_Name.)

Related

Syntax Error in INSERT INTO Statement (Error 3134)

I'm using MS Access 2013. My current issue is with the following code, I use to log user activity.
Table is called: tbl-activitylog and has five columns :
id
timestamps
Username
Activity
Additional
I checked code many times char after char and don't know what's wrong :(
TempVars("UserName").Value = "admin"
Logging("Logon", "system")
Public Sub Logging(Activity, Additional As String)
Dim sql_code As String
sql_code = "INSERT INTO tbl-activitylog(Username, Activity, Additional) VALUES('" & TempVars("UserName").Value & "','" & Activity & "','" & Additional & "')"
Debug.Print sql_code
CurrentDb.Execute sql_code
End Sub
Debug print shows:
INSERT INTO tbl-activitylog(Username, Activity, Additional) VALUES('admin','Logon','System')
Becaus of using "-" you have to do it in this way [tbl-activitylog]
sql_code = "INSERT INTO [tbl-activitylog](Username, Activity, Additional) VALUES('" & TempVars("UserName").Value & "','" & Activity & "','" & Additional & "')"
This 3134 error denotes a syntax error in your INSERT statement. As the name of your table contains a dash, you need to enclose it between brackets :
INSERT INTO [tbl-activitylog]
(Username, Activity, Additional)
VALUES('admin','Logon','System')
Generally speaking you may as well enclose all fields and table names, to avoid all risks of clashes with ms-access reserved words, like :
INSERT INTO [tbl-activitylog]
([Username], [Activity], [Additional])
VALUES('admin','Logon','System')
Consider a parameterized query, an industry best practice in any application layer language running SQL in any database. With QueryDefs, you can parameterize queries in MS Access.
Even more MS Access will not allow you to save queries with syntax issues. So, be sure to escape special characters and reserved words with square brackets or backticks.
SQL (save below as a query object)
PARAMETERS UsernameParam Text, ActivityParam Text, AdditionalParam Text;
INSERT INTO [tbl-activitylog] ([Username], [Activity], [Additional])
VALUES ([UsernameParam], [ActivityParam], [AdditionalParam])
VBA (reference above query and bind values without quotes or concatenation)
TempVars("UserName").Value = "admin"
Logging("Logon", "system")
Public Sub Logging(Activity, Additional As String)
Dim sql_code As String
Dim qdef As QueryDef
Set qdef = CurrentDb.QueryDefs("mySavedQuery")
' BIND PARAMS
qdef![UsernameParam] = TempVars("UserName")
qdef![ActivityParam] = Activity
qdef![AdditionalParam] = Additional
qdef.Execute dbFailOnError
Set qdef = Nothing
End Sub

MS Access / SQL : error in insert query statement

I am using MS Access 1997 version (.mdb file). On a daily basis, I need to insert values manually. In that file, there's a column Logical (Boolean data type). I am automate this template using SQL query instead of direct entry.
Below is my insert query:
Insert Into Data_CustomerTransmit_Tbl (Logical)
Values (" & Logicalnme & ")
Values:
Logicalnme - True
When I run this query in VBA in Excel, I get this error message
Syntax Error in Insert into Statement
Kindly confirm shall I use "Logical" as column name or this is the reserved keyword?
Thanks in advance.
There isn't a problem with your field name, you just need to enclose your INSERT column name in square brackets. You also need to choose a valid value in the VALUES clause:
INSERT INTO Data_CustomerTransmit_Tbl ( [Logical] )
VALUES (TRUE);
If you want to be prompted for the value to insert, you can use a parameter:
PARAMETERS [Please enter a Boolean value] YesNo;
INSERT INTO Data_CustomerTransmit_Tbl ( [Logical] )
VALUES ([Please enter a Boolean value]);
I presume you are trying to do this insert using VBA? If so, your syntax in building the SQL statement is correct, except you have some punctuation missing: double-quotes on each end.
"INSERT INTO Data_CustomerTransmit_Tbl (Logical) VALUES (" & Logicalnme & ")"
Further, as you have split the string over two lines (breaking before VALUES), you must also terminate the first line of the string with: ' " & _' (space,double-quote,space, ampersand, space, underscore) in order to indicate that the string continues to the next line. Then you begin the next line with double-quotes:
"INSERT INTO Data_CustomerTransmit_Tbl (Logical) " & _
"VALUES (" & Logicalnme & ")"
In VBA the code should look like this:
Docmd.RunSQL("INSERT INTO Data_CustomerTransmit_Tbl (Logical) VALUES (" & Logicalnme & ");"
The SQL query you alluded to - have you tried to execute it manually in the query editor using the same value(s) you are trying to pass from Excel? That would immediately provide more verbose feedback if there is an issue with the query or the data.
Regarding the Boolean field, make sure you are receiving a True/False that you are expecting, not a bit field, 0 and 1. I like to make quick log entries in a table or a file when troubleshooting to see the raw data.
Use Cbool function:
Insert Into Data_CustomerTransmit_Tbl (Logical)
Values (" & Cbool(Logicalnme) & ")
Add single quotes around values?
sql = "INSERT INTO Data_CustomerTransmit_Tbl (Logical) " & _
"VALUES ('" & Logicalnme & "')"
docmd.runsql sql

MS Access query assistance INSERT

This query keeps telling me I'm missing a semicolon at end of SQL statement, but when I add it, it tells me that there's a character found at the end of the SQL statement, what is wrong here? I'm used to working with SQL Server so this is just plain confusing to me. I'm not sure why Access needs to use a ";" to close the query. I'm just not sure where to include it.
strSQL = "Insert Into [tempCaseMgmt]Values([planID],[EdId],[OrID],[TheDate], [TypeID],[UserID],[TimeStart],[TimeEnd],[Unitsled],[Unitsid],[ClientID], [GenderID])" _
& " Select * from [dbo_tempDetail] where [userid]= " & [Forms]![frmx]! [txtClientID] & ";"
I'm just trying to make this work. The values I'm selecting and inserting are identical.
As suggested by #Martin in one of the comments to his answer, you are mixing up the two forms of INSERT INTO, specifically,
INSERT INTO ... VALUES ...
and
INSERT INTO ... SELECT ...
In my own simplified example this fails with "Run-time error '3137': Missing semicolon (;) at end of SQL statement."
Dim strSQL As String
strSQL = "Insert Into [tempCaseMgmt]Values([planID],[UserID])" _
& " Select * from [dbo_tempDetail] where [userid]=1" & ";"
Dim cdb As DAO.Database
Set cdb = CurrentDb
cdb.Execute strSQL, dbFailOnError
whereas this works
Dim strSQL As String
strSQL = "Insert Into [tempCaseMgmt] ([planID],[UserID])" _
& " Select * from [dbo_tempDetail] where [userid]=1" & ";"
Dim cdb As DAO.Database
Set cdb = CurrentDb
cdb.Execute strSQL, dbFailOnError
Note that the Values keyword has been omitted.
Without looking too deep into it, I would say, you are missing a white space directly in front of your select Statement.
Update:
You missed a second white space in front of the "Values" keyword. Did you copy pasted this query, or did you just wrote it in?
I would say, that you try to use a mixed up statement syntax for the Insert Into Statement. Values is used for single record appending. That means you should have an semicolon after the closing parenthesis. For the interpreter the Select is a completely new Statement. I goes that is not what you want.
Use the multi record syntax for insert into:
"Insert Into [tempCaseMgmt] \n
Select * from [dbo_tempDetail] where [userid]= " & [Forms]![frmx]![txtClientID] & ";"
In this case column naming should be identically
best regards
Martin

"Insert Into" syntax error?

Using Access 07 -"Insert INTO" using SQL: In the attached script it inserts data into another table, but only if I remove the OCC_Scenario. I need OCC_Scenario and many more values.
The error is a Syntax error but I have tried every combination. Can anyone see a syntax error?
SSql = "Insert INTO tbl_transactions (Caseid,OCC_Scenario,RoleId) Values ('" & CaseId & "',[OCC_Scenario]" ',
SSql = SSql & "', 'SR');"
DoCmd.RunSQL SSql
The apostrophe and comma at the end of the first line look inappropriate.

parameterized query not working in VB

statement = "SELECT OrderID, (SELECT VendName FROM Vendors WHERE Vendors.VendorID = Orders.VendorID) " &
",OrderDt, RcvdDt, OrderTotal " &
"FROM Orders " &
"WHERE VendName=? " &
"ORDER BY OrderDt DESC"
Dim cmd As New OleDbCommand(statement, connection)
cmd.Parameters.AddWithValue("VendName", txtVendorFilter.Text)
Dim reader As OleDbDataReader = cmd.ExecuteReader(CommandBehavior.Default)
I was trying to do this before by simply concatenating the textbox value right into the SQL and I was getting a "No values given for required parameters", and read that that I should use parameterized queries instead. So I tried this and it doesn't give me any errors, but the reader never has anything in it. I've never used parameterized queries before, so I'm a bit lost as to why this isn't working.
Edit:
I've changed the above code to account for OLEDB from what I briefly read on how it should work, and it's giving me the "no values given for required parameters" again.
One problem is here:
"WHERE VendName='#x' " &
Drop the ' marks - the parameterization will take care of this for you:
"WHERE VendName= #x " &
Using the ' in the query means that '#x' is treated as a string type, not a parameter name.
Additionally, since you are using OleDb, names parameters are not supported. You need to use ? to signify a parameter in the query:
"WHERE VendName= ? " &