I got this error everytime I try to save the text in this field to the database. The code is this:
Dim strInsert As String
strInsert = "INSERT INTO Dbase (EB3_30) VALUES ('" & Me.EB3_30 & "')"
CurrentDb.Execute strInsert
The debugger stops at the last line and I get this error (I'm going to traduce it because it's in spanish):
run time error '3075':
Syntax Error (Missing Operator) in query expression "value of EB3_30"
The value of EB3_30 is a string of aproximate length 250. As it's in spanish some letters have accents. I also use dots, apostrophes and slashes. Maybe some of this characters cause problems? Any ideas?
Apostrophes probably cause problem.
Try this:
strInsert = "INSERT INTO Dbase (EB3_30) VALUES ('" & Replace(Me.EB3_30, "'", "''") & "')"
Related
I am having some trouble formatting an SQL string in Access, I can never seem to debug these syntax issues with SQL strings. I have this string:
strSQL = "SELECT * FROM FXData WHERE ShortCode=" & Forms!FXVolatility.cboCurve.Value & " AND MaxOfMarkAsOfDate=#" & MaxOfMarkAsofDate & "# ORDER BY MaxOfMarkAsOfDate "
debug.print strSQL
Set rs = CurrentDb.OpenRecordset(strSQL, Type:=dbOpenDynaset, Options:=dbSeeChanges)
which prints
SELECT * FROM FXData WHERE ShortCode=USD.XS AND MaxOfMarkAsOfDate=#3/31/2016# ORDER BY MaxOfMarkAsOfDate
However this gives me a "Too Few Parameters, expected 1" error.
All the fields and their associated values that are referenced in strSQL exist in the referenced table. What could the error be?
Also if you've got any resources on how to debug/identify these specific access SQL formatting issues I'd be happy to hear them.
In SQL, strings need to be put in single or double quotes. Thus, your output should look like this:
... WHERE ShortCode='USD.XS' ...
Thus, your code becomes:
strSQL = "SELECT * FROM FXData WHERE ShortCode='" & _
Replace(Forms!FXVolatility.cboCurve.Value, "'", "''") & _
"' AND MaxOfMarkAsOfDate=#" & MaxOfMarkAsofDate & _
"# ORDER BY MaxOfMarkAsOfDate "
The Replace ensures that any single quotes occurring within cboCurve.Value are properly escaped.
Note that it is recommended to use parameters instead of string concatenation to "fill" values into an SQL statement. An example for how to do this in MS Access can be found in the answer to this question:
VBA OpenRecordset Producing Too few parameters. Expected 2. Error
letter=65
is a variable representing a letter (A) in the alphabet.
I want to insert letter into part of an sql command string:
sqlUrlCount = "SELECT tblMain.Name FROM tblMain WHERE (((tblMain.Name) Like '" & Chr(letter) & "*'))"
but I get an error: "Run-time error '3075': Syntax error in string in query expression '(((tblMain.Name) Like".
this is probably because of the quotes and double quotes I used. but how else can I do this?
Your syntax is correct so try to copy-n-paste the resulting string:
SELECT tblMain.Name FROM tblMain WHERE (((tblMain.Name) Like 'A*'))
into a new query.
If it fails, adjust the SQL and then your code.
If it runs, then rewrite your code line (no copy-n-paste), then delete the old code line.
When I tried to create a field called 'Name' in Access it complained that it was a reserved word - could be part of the problem.
The code below returned an SQL string which worked when I pasted it into the query window (note - have updated 'Name' to 'sName' and the field type is Text).
Also note - Access loves putting brackets around everything and most of the time they're not required.
Sub test()
Dim letter As Long
Dim sqlUrlCount As String
letter = 65
sqlUrlCount = "SELECT sName FROM tblMain WHERE sName Like '" & Chr(letter) & "*'"
End Sub
Edit:
To use a SELECT query:
Sub Test()
Dim sqlUrlCount As String
Dim letter As Long
Dim rst As DAO.Recordset
letter = 65
sqlUrlCount = "SELECT tblNewMain.WebAddressCompareString, " & _
"Count(*) AS [How Many?] FROM tblNewMain " & _
"WHERE (((tblNewMain.WebAddressCompareString) Like '" & Chr(letter) & "*')) " & _
"GROUP BY tblNewMain.WebAddressCompareString HAVING (((Count(*))>1))"
Set rst = CurrentDb.OpenRecordset(sqlUrlCount)
With rst
If Not .BOF And Not .EOF Then
.MoveFirst
Do
Debug.Print .Fields("WebAddressCompareString") & " : " & .Fields(1)
.MoveNext
Loop Until .EOF
End If
.Close
End With
Set rst = Nothing
End Sub
If it's a DDL or DML type query - i.e. UPDATE, CREATE TABLE, SELECT INTO, etc then you can use DoCmd.RunSQL
I have created a form in Access 2010 that is used to insert data into an existing table. The table contains a Keywords field, Source combo box, and a Code text box where i write the data to be inserted and there is a button for executing the query. The code for the form is:
Private Sub cmd_go_Click()
Dim insertstring As String
insertstring = "INSERT INTO KWTable (KW, Source, Code) VALUES('" & text_key.Value & "','" & combo_source.Value & "','" & txt_code.Value & "');"
DoCmd.RunSQL insertstring
End Sub
The code is simple, it inputs the data to the table so i can reference it for future use. Now the problem I am having is that when I try to add long bits of code that I use in SQL Server i get a syntax missing expression error which I am assuming is coming from the single quotes since the code is from SQL. I am getting the error because when i am trying to store a code i used in SQL Server it uses single quotes which access does not recognise. I think if I try to write in the code for the insert form something to help convert the single quotes into double quotes, then reconvert them back to single quoteswill help solve the problem. I just cant figure out how to do it and could really use some help.
Thank You
You can avoid trouble with included quotes in your inserted text by using a parameter query.
Consider an approach such as this for cmd_go_Click().
Dim strInsert As String
Dim db As DAO.database
Dim qdf As DAO.QueryDef
strInsert = "PARAMETERS pKW TEXT(255), pSource TEXT(255), pCode TEXT(255);" & vbCrLf & _
"INSERT INTO KWTable (KW, Source, Code) VALUES (pKW, pSource, pCode);"
'Debug.Print strInsert
Set db = CurrentDb
Set qdf = db.CreateQueryDef(vbNullString, strInsert)
qdf.Parameters("pKW") = Me.text_key.value
qdf.Parameters("pSource") = Me.combo_source.value
qdf.Parameters("pCode") = Me.txt_code.value
qdf.Execute dbFailOnError
Set qdf = Nothing
Set db = Nothing
However, I don't understand how JoinCells() fits in.
I use a function that handles Null Values, and escapes single quotes (by converting them to two single quotes) when creating SQL statements directly:
Function SafeSQL(ByVal pvarSQL As Variant) As String
SafeSQL2 = Replace(Nz(pvarSQL, ""), "'", "''")
End Function
Then in your routine you would have:
insertstring = "INSERT INTO KWTable (KW, Source, Code) VALUES('" & SafeSQL(text_key.Value) & "','" & SafeSQL(combo_source.Value) & "','" & SafeSQL(txt_code.Value) & "');"
I have a form, and I want to fill it, and then save some of the fields into an existing table called Order.
I'm trying to do this with this line of code:
CurrentDb.Execute "INSERT INTO Order (OrderNumber)" & " VALUES (' " & Me.order & " ')"
I have also tried it like this
CurrentDb.Execute "INSERT INTO Order (OrderNumber)" & " VALUES ( " & Me.order & " )"
but it doesn't seem to make a difference. I keep getting the following error:
run-time error '3134': syntax error in INSERT INTO statement.
what am I doing wrong?
Order is a reserved word. If you must keep that as the table name, bracket it to avoid confusing the db engine.
Dim strInsert As String
strInsert = "INSERT INTO [Order] (OrderNumber) VALUES ('" & Me.order & "')"
Debug.Print strInsert
CurrentDb.Execute strInsert, dbFailOnError
If OrderNumber is numeric data type instead of text, discard those single quotes from the INSERT statement.
Store your statement in a string variable. Then use Debug.Print to examine the completed statement you're asking the engine to execute. You can view the Debug.Print output in the Immediate window. Go there with Ctrl+g Copy the statement and paste it into SQL View of a new Access query for troubleshooting.
I was just testing my database and I realized that I run into problems wherever a text entry in my database contains a ' character (single quote). My solution for now is that before any .execute operations on a string, I call escape(string, "'", " "'" ").
Summarized example below:
qr = "INSERT INTO tblExample VALUES ( " & "'" & me.testparam & "'" & ");"
qr = Replace(qr, "'", " "'" ")
db.execute qr
'also tried qr = "INSERT INTO tblExample VALUES ( " & "'" & replace(me.testparam,"'"," ") & "'" & ");"
This was what I assumed to be the correct workaround to prevent errors from values such as Tourette's.
There's two problems with this. First of all, it's not working. Second, I have over 50 locations in code throughout my app where I call the statement db.execute qr where qr is a string that could potentially contain a single quote. I need the field in the table to contain the single quote, so I can't just replace it with a space or something similar.
Two part question:
Is there a better solution than going through all of my code calling Replace on every string that is to be executed as a query?
Why is my current implementation failing? - I still get syntax error in query expression even when escaping the single quote to a space.
First examine these 2 lines.
"VALUES ( " & "'" & me.testparam & "'" & ");"
"VALUES ( '" & me.testparam & "');"
Both will produce the exact same string. The difference for me is that my brain comprehends the second version faster.
Now, here is what the comments are telling you to do ... replace each single quote in your source string with two single quotes. I added Debug.Print so you can view the finished string in the Immediate window (go there with Ctrl+g) ... you can then see the actual string rather than trying to imagine what it looks like.
qr = "INSERT INTO tblExample VALUES ( '" & _
Replace(Me.testparam, "'", "''" & "');"
Debug.Print qr
db.Execute qr, dbFailOnError
Since I assumed db is a DAO.Database object variable, I included the dbFailOnError option. You should include an error handler in your code to deal with any problems dbFailOnError exposes.
When you run into trouble with a VBA function in a query, drop to the Immediate window and test your function expression there. This one triggers a compile error, "Expected: list separator or )":
? Replace("Tourette's", "'", " "'" ")
But this one works:
? Replace("Tourette's", "'", "''")
Tourette''s
I mentioned that because it's useful in general, and also because your title starts with "Escaping unwanted characters, mainly single quotes". So if you want to remove/replace other characters, not just single quotes, experiment in the Immediate window until you find a Replace() expression which works. Then use that expression in your query.
For example, if unwanted characters include line breaks ...
MyString = "foo" & vbCrlf & "bar" : ? MyString
foo
bar
? Replace(MyString, Chr(13) & Chr(10), " ")
foo bar
Note: I used Chr(13) & Chr(10) rather than vbCrlf as the find target because the db engine can use the Chr() function but doesn't know about the named constant (vbCrlf).
Your query is failing because you have not said where to insert :
Dim qd As QueryDef
qr = "INSERT INTO tblExample (AText) VALUES ( [avalue] );"
Set qd = CurrentDB.CreateQueryDef("",qr)
qd.Parameters("avalue").Value = me.testparam
qd.Execute dbFailOnError
Another method is to define a quote as constant (Const Quote = """") and use that to build SQL Statements. It is not possible to define a quote as Const Quote = Chr(34) as a constant definition can't be based on a function so one has to use four double quotes in a row. The third quote is what you are saving, the second quote is to excape the third quote and the first and last quote are because the value you are assigning is a string.
You will then be able to build SQL statements such as:
SQL = SELECT * FROM tblSyndromes
WHERE Syndrome = " & Quote & "Tourette's" & Quote & ";"
It will no longer matter that there are single quotes in your data.
I don't use parameters as if I upscale my database to sql server and convert my queries to pass-through queries, I can't use parameters. I rarely upscale but I write all my code with that assumption. Also if your query is not working as expected, how do find out what went wrong. If I have a variable called SQL, then I can always print the SQL statement and run it in a new query to see what it does.