Jason
Jason

Reputation: 1977

Error using Query Parameters with cfscript query

Here is my code:

var qryStr = "
            UPDATE templates_email 
            SET title = :title, test_emails = :testEmail, body = :body
            WHERE id = :templateID";

q = New Query();
q.setSQL(qryStr);
q.addParam(name="title", value="#arguments.title#", cfsqltype="cf_sql_char");
q.addParam(name="body", value="#arguments.templateContent#", cfsqltype="cf_sql_char");
q.addParam(name="testEmail", value="#arguments.test_emails#", cfsqltype="cf_sql_char");
q.addParam(name="templateID", value="#arguments.id#", cfsqltype="cf_sql_integer");

return q.execute().getResult();

This is the error:

Parameter 'body WHERE' not found in the list of parameters specified

SQL: UPDATE templates_email SET title = :title, test_emails = :testEmail, body = :body WHERE id = :templateID

The error occurred in C:\ColdFusion9\CustomTags\com\adobe\coldfusion\query.cfc: line 108

I can only assume I have done something wrong with the way my SQL is structured with the parameters, but can't work out what it is. Can anyone see what I am doing wrong here?

Upvotes: 10

Views: 3461

Answers (3)

user3071284
user3071284

Reputation: 7100

ColdFusion can get confused when parsing the SQL string to use parameters. The easiest way to solve this shortcoming is to put a space after each of your parameters.

Since some text editors may remove trailing whitespace, like when saving, I include an empty comment after any space at the end of a line.

var qryStr = "
    UPDATE templates_email 
    SET title = :title , test_emails = :testEmail , body = :body /**/
    WHERE id = :templateID /**/
";

Upvotes: 0

Mark Mandel
Mark Mandel

Reputation: 1336

The parser for getting the params doesn't tokenize on return values, only on whitespace (which is really annoying). Try the following:

var qryStr = "
    UPDATE templates_email 
    SET title = ( :title ), test_emails = ( :testEmail ), body = ( :body )
    WHERE ( id = :templateID )
";

The ( and ) should remove any issue with where the parser not being able to recognise where the :params stop and start.

Upvotes: 16

Peruz Carlsen
Peruz Carlsen

Reputation: 582

This error occurs because of the tab and line break characters found in your SQL statement. I normally run below function on my SQL statement to remove these characters.

string function cleanSQL(required string sqlStatement)
    output="false"
{
return trim(reReplace(arguments.sqlStatement, "\t|\n", " ", "all"));
}

So, your setSQL() can look like:

q.setSQL(cleanSQL(qryStr))

or simply:

q.setSQL(reReplace(qryStr, "\t|\n", " ", "all"))

Upvotes: 6

Related Questions