I'm using Replace function in SQL query, it is working in access sql query design mode but not working in access VBA. Throwing expected end of statement. I tried all the ways but not working. CM column has a string like this ;#WR_1;#WR_2;#WR_3;#WR_4;# and I'm trying to get value WR_2 where ever the string occurs in CM column
strSQL = "SELECT * FROM WT_table " & _
"WHERE [CM] IS NOT NULL " & _
"AND (';' & Replace([CM], '#', "") & ';') Like '*;WR_2;*'; ;"
Just remove the second semi-colon (;) from the end of the last line - you have two of them, making it appear that there are multiple statements to be executed.
"AND (';' & Replace([CM], '#', "") & ';') Like '*;WR_2;*';"
In addition, as pointed out by simoco, you have a pair of double-quotes in your Replace function. I'm not certain whether you mean to have two single-quotes or not, but this would be the right code to use in that case:
"AND (';' & Replace([CM], '#', '') & ';') Like '*;WR_2;*';"
Related
I have a table with 4 columns and update them through excel user form and all are varchar (255). when I try to enter the character ' I get syntax error, mysql doesn't accept it... What am I doing wrong here, do I need to change datatype
Update: I figured that the problem is not with MySQL (obviously :) ) but my code to update the table.
Dim sq As String
sq = "UPDATE sample.`nov-21` SET `Site work being carried out`='" & sitecombo.value & "',`Group`='" & eqgrp.value & "',`Description`='" & desc.value & "',`T Number`='" & tn.value & "', WHERE sample.`nov-21`.`ID`= " & Me.IDnum & ";"
Escape ' with \ or another ': 'O''Malley' or 'O\'Malley'
When you write 'O'Malley', MySQL read string literal 'O' followed by name Malley (which is not recognized) and a ' with no meaning, hence the syntax error.
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
I am trying to pass in a string to an Access query that has a parameter "companyType" . The sql is "where companyType in ([forms]![formname].[fieldname])"
This works fine with one value but for string e.g "CompanyType1","CompanyType2" it does not work.
I know the in operator needs to have each element in quotes if the data type for that field is a Short Text or Long text type. I have tried wrapping them in single quotes also to no avail.
When I hard code the values in the query e.g "in ('CompanyType1','CompanyType2')" query returns rows so I believe it is something with escaping the quotes but not exactly sure.
You won't be able to put this into an access query as a parameter; However you could build the query in vba:
dim qry as new QueryDef
qry.SQL = _
"SELECT some_column, ... " & _
"FROM some_table [INNER JOIN ...] " & _
"WHERE CompanyType IN (" & [list] & ")"
qry.Execute
I have a form that filters data by user, date range and specific value for a column, depending if checkbox is ticked or not, as below;
strWhere = " WHERE [user] in (" & Left(strIN, Len(strIN) - 1) & ") And [Month] Between [forms]![frm_user]![txtStartDate] And [forms]![frm_user]![txtEndDate]"
If Me!checkbox = True Then
strtcheck = " (Satified Vs Dissatisfied Like Dissatisfied) "
End If
strSql = strSql & strwhere & strtcheck
So what I want and I can't get it to work is, if Me!checkbox is true, than the Satified Vs Dissatisfied must be equal to Dissatisfied and then I want to pass it to the strSql, however when i run it in Access it doesn't work, can someone help?
If your string is intended to include a WHERE condition for a field named Satified Vs Dissatisfied, enclose the field name in square brackets. And enclose the string you compare to the field in quotes.
strtcheck = " ([Satified Vs Dissatisfied] Like 'Dissatisfied') "
Actually that condition doesn't use pattern matching, so you could just use = instead of Like.
strtcheck = " ([Satified Vs Dissatisfied] = 'Dissatisfied') "
Also you likely need to include SQL AND to combine that condition with the other WHERE conditions.
strtcheck = " AND ([Satified Vs Dissatisfied] = 'Dissatisfied') "
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.