Pass in Delimited String to Access Query as Parameter - ms-access

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

Related

How do I pass SQL a double as a parameter?

I'm trying to run this code:
Set Lrs = db.OpenRecordset("Select [LastName]" & _
"From ['Chromebook Registration Form]" & _
"Where [InventoryNumber] = dbInventoryNumber ")
Where "dbInventoryNumber" is a double variable. The field [InventoryNumber] takes a double, but when I run this I get a 3061 Run-time error. Too few arguments. Expected 1.
I know how to pass string variables as parameters, but how do I do it for doubles?
Thanks!
Although the [ ]s will allow the SQL to evaluate, should include space at end of each continued line so SQL string doesn't run together when compiled. Pass double variable same way as string except don't use apostrophe delimiters. (Date/time field parameters use # delimiter.) Don't put variables within quote marks, concatenate them. Remove apostrophe in front of source (assuming this is not really in source name - advise no spaces nor punctuation/special characters in naming convention). Source name that includes word "Form" sounds like name of a form. Source must be a table or query.
Set Lrs = db.OpenRecordset("Select [LastName] " & _
"From [Chromebook Registration Form] " & _
"Where [InventoryNumber] = " & dbInventoryNumber)

strSQL formatting in Access

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

Escaping unwanted characters, mainly single quotes --replace function and implementation

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.

Passing argument to a function in a query ACCESS

I am trying to use a function in my query in Access 2007 as following:
Function_Name('Query_1,'Field_1', Value_1, _
'Date_Month=#' & [Date_Month] & '# and Code="' & [Code] & '"')
The function gives an error because of the last argument: 'Date_Month=#' & [Date_Month] & '# and Code="' & [Code] & '"'.
Is there anything wrong with the code of the last argument?? Please help.
Thanks,
First of all, I think you've got your quotes messed up. It's not clear from your question whether you are calling or trying to declare a function, so I assume you are trying to call the function. In VBA, you need to use double quotes, and in the Access query, you should single quotes for strings.
Function_Name(Query_1, Field_1, Value_1, "Date_Month=#" & _
[Date_Month] & "# and Code='" & [Code] & "'")
However, it is unclear exactly what the different parameters are referencing (variable names?), or why the fourth parameter is a string with the Date_Month and Code WHERE clause passed in.
Note, when you are searching for a date, it is #date# syntax, not #'date'#.
For example:
"Date_Month=#" & [Date_Month] & "#"

MS-Access 2003 - Expression in a Text Box on a form

just wondering when using an expression on a form in a text box, to return a value from a table, can the expression have multiple tables in the expression to return the value?
the tables are linked and I can return the value in a query, so I figured that Access would be able to do it with this method as well????
=DSum("[tblMain]![Revenue]","tblMain","[tblMain]![Quarter]=3 AND [tblMain]![Region]='NorthEast'" AND [tblOffice]![Location]='NewYork'")
this is the expression that I entered into my text box, without the reference to the 2nd table it works fine, but once I had it, I get the flickering error message in the text box (just as on a report)......
I know this method is probably used more in reports than forms, but I am novice, and trying to come up with a dashboard solution that returns lots of facts quickly per department. I am using this in the "Control Source" field of the data tab of the properties window, not VB. Mainly because I do not know how to get it to work with VB.
Thanks for the help as always!
As far as I know, you cannot refer to more than one table or query in a domain aggregate function. As grazird says, how are these tables related? Let us say it is on tblMain ID, you can build a query called, say, qryMainOffice, the SQL (SQL View, Query Design window) would look something like:
SELECT [tblMain].[Revenue],[tblMain]![Quarter],[tblMain]![Region],
[tblOffice]![Location]
FROM tblMain
INNER JOIN tblOffice
ON tblMain.ID = tblOffice.MainID
DSum would then be (remove line break):
=NZ(DSum("[Revenue]","qryMainOffice",
"[Quarter]=3 AND [Region]='NorthEast' AND [Location]='NewYork'"),"Not found")
You could also use a recordset or query in VBA to return the value.
EDIT re COMMENT
To use the above in VBA, you either need to add parameters or use a string:
''Reference: Microsoft DAO 3.x Object Library
Dim rs As DAO.Recordset
Dim db As Database
Dim strSQL as String
Set db= CurrentDB
strSQL = "SELECT Sum(t.[Revenue]) As TotalNY" _
& "FROM tblMain t " _
& "INNER JOIN tblOffice o " _
& "ON t.ID = o.MainID " _
& "WHERE t.[Quarter]=3 AND t.[Region]='NorthEast' " _
& "AND o.[Location]='NewYork' " _
'' I have use aliases for simplicity, t-tblMain, o-tblOffice
'' If you wish to reference a control, use the value, like so:
'' & " AND [Location]='" & Me.txtCity & "'"
'' Dates should be formated to year, month, day
'' For joins, see http://www.devshed.com/c/a/MySQL/Understanding-SQL-Joins/
Set rs = db.OpenRecordset strSQL
If Not rs.EOF Then
Me.txtAnswer = rs!TotNY
Else
Me.txtAnswer = "N/A"
End If
You can also use different queries to return several results that can be shown with a list box or a subform:
strSQL = "SELECT TOP 5 o.[Location]," _
& "Sum(t.[Revenue]) AS TotRevenue" _
& "FROM tblMain t " _
& "INNER JOIN tblOffice o " _
& "ON t.ID = o.MainID " _
& "WHERE t.[Quarter]=3 AND t.[Region]='NorthEast' " _
& "GROUP BY o.[Location]"
The above would return revenue for quarter 3 for all locations in NorthEast region. If you want the top values of each group, you are looking at a more complicated query, which I will leave for now.
How are these tables related? Can you describe the relationship and any primary/foreign keys?
Also, referencing the table name is not necessary in the first parameter of this function (since it is already taken care of in the second one).
For example, your code could be:
=DSum("Revenue","tblMain","Quarter=3 AND Region='NorthEast'" AND [tblOffice]![Location]='NewYork'")
Just trying to save you some keystrokes and increase its readability. :)