0

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.

1 Answer 1

3

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:

Sign up to request clarification or add additional context in comments.

1 Comment

thank you that fixed the problem! I appreciate the resource as well

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.