Syntax error creating an SQL query dynamically - sql

I'm using VB6 and MS Access. my sql command is
insert into BatchInfo (BName,BDate,Currency) values('" & Me.txtBatchName.Text & "','" & Me.dtpBatchDate.Value & "','" & Me.cboCurrency.Text & "')
the output of the command at run time is
"insert into BatchInfo (BName,BDate,Currency) values('batch1','8/2/2012','AED')"
here is the schema of the BatchInfo Table
BatchID AutoNumber
BName Text
BDate Date/Time
Currency Text
I cannot find any syntax error. Please help.

Currency is a reserved word, escape it thusly;
insert into BatchInfo (BName, BDate, [Currency]) values (...

MS Access typically likes # signs around its dates:
insert into BatchInfo (BName,BDate,Currency)
values('" & Me.txtBatchName.Text & "','#" & Me.dtpBatchDate.Value & "#','" & Me.cboCurrency.Text & "')

You are using single quotes, not double quotes.
Try this
insert into BatchInfo (BName,BDate,Currency) values(""" & Me.txtBatchName.Text & """,#" & Me.dtpBatchDate.Value & #",""" & Me.cboCurrency.Text & """)

Related

Run-time error 3134 "Syntax error in INSERT INTO statement"

I am for the first time posting question in this platform. Currently, I am running into a problem of executing my assignment of online shopping database. When I try to register an account into it, it always pops up a window say run-time 3134 error, syntax error in INSERT INTO statement. I was trying any possibilities in order to solve the problem but it won't work. So, any solution to counter this problem? Thanks for your many helping. 😊
Here is my codes:
CurrentDb.Execute "INSERT INTO Login table (FirstName,LastName,Gender,UserName,Password,Email,Phone) VALUES ('" & Me.FirstName & "','" & Me.LastName & "','" & Me.Gender & "','" & Me.UserName & "', '" &
Me.Password & "','" & Me.Email & "','" & Me.Phone & "')"
Presuming that the table you're trying to INSERT INTO is named Login Table, you have a space in the table name, which means any time you reference that table you need to surround it in square brackets.
CurrentDb.Execute "INSERT INTO [Login table]` (FirstName,LastName,Gender,UserName,Password,Email,Phone) VALUES ('" & Me.FirstName & "','" & Me.LastName & "','" & Me.Gender & "','" & Me.UserName & "', '" &
Me.Password & "','" & Me.Email & "','" & Me.Phone & "')"
This is one of the main problems with naming your table with spaces. Also, Login table is an especially bad name - you already know it's a table, so why do you need to repeat that information in the table name? And if you insist on using table names that are more than one word, you should use an underscore rather tha a space (like Login_table) to reduce the work involved with every query and prevent problems like the one you're having here.
Consider using a stored query that points to the form controls as parameters and avoid VBA variable concatenation and quote punctuation. Also, query design in Access GUI does not allow users to save query with syntax errors.
SQL
Adjust myForm to actual form name.
INSERT INTO [Login table]
(FirstName,
LastName,
Gender,
UserName,
Password,
Email,
Phone)
VALUES
(Forms!myForm!FirstName,
Forms!myForm!LastName,
Forms!myForm!Gender,
Forms!myForm!UserName,
Forms!myForm!Password,
Forms!myForm!Email,
Forms!myForm!Phone)
VBA
No need to close action queries and add SetWarnings to avoid update prompts.
DoCmd.SetWarnings False
DoCmd.OpenQuery "mySavedAppendQuery"
DoCmd.SetWarnings True
Password is a reserved word, so:
CurrentDb.Execute "INSERT INTO [Login table] (FirstName,LastName,Gender,UserName,[Password],Email,Phone) ...
I have just found that the the table had a field that was using a reserved name Note. By placing it in `` quotes (Note) fixed the issue.

using what I think is a variable in a SQL statement

I am very new to SQL and think I have a simple problem but was unable to figure it out from other posts. I have the following code:
INSERT INTO tblShortScores ( TradeNum, FilterNum, Rank, ScoreNum )
SELECT [Forms]![frmOpenTrades]![TradeNum] AS TradeNum, tblFilters.FilterNum, tblFilters.SBBExh AS Rank, tblFilters.SBBExh AS Score
FROM tblFilters
WHERE (((tblFilters.SBBExh) Is Not Null));
but instead of using the literal "SBBExh" in tblFilters.SBBExh, I want to do something like
tblFilters.("S" & [Forms]![frmOpenTrades]![Strategy])
where something like
[Forms]![frmOpenTrades]![Strategy] contains the value "BBExh".
It's in MS Access and I seem unable to find a syntax that works
any help is appreciated
Can't dynamically build field name in query object. Use VBA to construct and execute action SQL, like:
strField = "S" & Me.Strategy
CurrentDb.Execute "INSERT INTO tblShortScores (TradeNum, FilterNum, ScoreNum) " & _
"SELECT " & Me.TradeNum & " AS TradeNum, FilterNum, " & strField & " " & _
"FROM tblFilters WHERE " & strField & " Is Not Null;"
Assumes TradeNum is number type - if it is text, use apostrophe delimiters:
SELECT '" & Me.TradeNum & "' AS .
If SQL injection is a concern review, How do I use parameters in VBA in the different contexts in Microsoft Access?

SQL Statement to grab data from entry form to Data table in Microsoft Access 2010 VBA

So I'm setting up a database in MS Access 2010 (first time doing this). I can't seem to get the syntax of the SQL statement right. I want to take the data I have entered into a data entry form and insert a new row into a table, with that data. All of this using SQL in the VBA editor (only code I have available, all others are blocked)
Private Sub Add_Click()
Dim sSQL As String
sSQL = "INSERT INTO Data (Type, Name, Quantity, Amount, Class, Series, Client, Date1, Date2) VALUES " & _
"('" & Me!txtType & "','" & Me!txtName & "'," & Me!txtQuantity & "," & Me!txtAmount & ",'" & Me!txtClass & "','" & Me!txtSeries & "','" & Me!txtClient & "'," & Me!date1 & "," & Me!date2 & ")"
Debug.Print sSQL
CurrentDb.Execute sSQL
End Sub
So i Get the following error when i run the code, from the VBA editor :
"Run-time error '3134':
Syntax error in INSERT INTO statement."
And the printout of the SQL statement looks correct :
INSERT INTO Data (Type, Name, Quantity, Amount, Class, Series, Client, Date1, Date2)
VALUES ('Purhcase', 'TV', 500, 100, '', '', ' Bob', 05.08.2019, 05.08.2019)
Found the answer :
turns out one of the names of my data fields was a reserved word, therefore i simply put them all into [] and it solved the issue.
Thanks anyways for the help guys!

SQL VBA syntax issue

This select statement works.
rs.Open "Select Company from Customers where Company LIKE '" & Replace(Range("K4").Value, "'", "''") & "%' "
This select statement doesn't work.
rs.Open "Select Company from Customers where '" & Range("N4").Value & "' LIKE '" & Replace(Range("K4").Value, "'", "''") & "%' "
I'm going to have a data validation drop down box where the user can pick between a few options so being able to change the second Company in the first select statement to the users selection would be handy. Something is wrong with the syntax because although it doesn't give me any errors it doesn't have any results.
You shouldn't quote the column name - notice there are no quotes in your first example.
rs.Open "Select Company from Customers where " & Range("N4").Value & _
" LIKE '" & Replace(Range("K4").Value, "'", "''") & "%' "

An explicit value for the identity column in table 'tableX' can only be specified when a column list is used and IDENTITY_INSERT is ON."

I am getting the error above saying that I cannot explicitly define the identity column without doing these things however, I am not trying to set the value of the identity column. I am merely trying to execute a basic insert statement using user input. I'm really stuck and need to get past this. Thoughts?
Public Sub ExecuteSQL(ByVal sql As String)
Using myConnection As New Data.SqlClient.SqlConnection(connString)
myConnection.Open()
Using cdmDatabaseCommand As New Data.SqlClient.SqlCommand(sql, myConnection)
cdmDatabaseCommand.ExecuteNonQuery()
End Using
End Using
End Sub
Dim insertSpray As String = ""
insertSpray = "INSERT INTO Spray VALUES ('" & sprayDate & "','" & timeStart & "','" & timeFinish & "','" & tankVolumeStart & "','" & tankVolumeFinish & "','" & comment & "','" & vehicleId & "','" & vehicleTime & "','" & siteType & "','" & area & "','" & applicatorOneId & "','" & applicatorTwoId & "','" & sprayLocationFeature & "','" & sprayStartLocationDescription & "','NULL','NULL','NULL','NULL','" & sprayEndLocationDescription & "');"
ExecuteSQL(insertSpray)
You're not specifying a column-list, so SQL Server assumes you want to insert into all columns, in table-order.
You need to change your syntax to specify the names of the columns you're inserting into (and leave out the identity column, obviously):
insert into Spray (SprayDate, TimeStart, ...)
values (...
Also note that your code is vulnerable to SQL injection attacks. You should look into using parameterized queries.
Try to explicitly make the columns of table Spray without the identity column.
Something like this:
insertSpray = "INSERT INTO Spray(Column1, Column2,...) VALUES (Value1,Value2,..)"