Skip to main content
Known Participant
October 12, 2009
Question

Using a string variable as a query SQL statement

  • October 12, 2009
  • 1 reply
  • 1564 views

I want to construct a custom SQL statement in a string var, then use that var in the cfquery statement.  What is the proper syntax?  Here is my feeble attempt:

  <cffunction ...>

  <cfset var sql_txt="">

        <cfquery name="qSBJs" datasource="cfBAA_odbc">
            "#sql_txt#"
        </cfquery>

    <cfreturn qSBJs>

--------------------------------------------

I've tried using no " or # or just # or just " but nothing works.

what about:

        <cfquery name="qSBJs" datasource="cfBAA_odbc" sql="#sql_txt#">
           
        </cfquery>

nope.  I wish there was a sql property I could fill *before* the execution of the query.  Any suggestions?

    This topic has been closed for replies.

    1 reply

    Inspiring
    October 12, 2009

            <cfquery name="qSBJs" datasource="cfBAA_odbc">
                "#sql_txt#"
            </cfquery>

    You have to remember two things here:

    1) Everything between the cfquery tags is passed to the DB driver.  Even if your sql_text string was syntactically correct, would you want to be wrapping it in quotes?  No.  The string between the CFQUERY tags should resolve to valid SQL.

    2) CF by default escapes single quotes in variable values when the variable is used within <cfquery> tags.  This is an attempt to minimise SQL injection.  However if your variable holds your entire SQL string, you probably DO NOT want the single quotes escaped across the board.

    I've tried using no " or # or just # or just " but nothing works.

    When something "doesn't work", make sure to tell us why you think it's not working, eg any error message, or the screen is blank, or it does something odd, or what.  There are plenty of ways for something to "not work".

            <cfquery name="qSBJs" datasource="cfBAA_odbc" sql="#sql_txt#">

    You could have circumvented that experiment completely by reading the docs first:

    http://livedocs.adobe.com/coldfusion/8/htmldocs/Tags_p-q_17.html#1102316

    The docs will always state all the available attributes.  There's no SQL attribute.

    nope.  I wish there was a sql property I could fill *before* the execution of the query.  Any suggestions?

    What version of CF are you using?  If it's CF9, you can use the Query Service too:

    http://help.adobe.com/en_US/ColdFusion/9.0/CFMLRef/WSe9cbe5cf462523a0693d5dae123bcd28f6d-7ffb.html

    However there's nothing wrong with simply passing a string variable through to a <cfquery> call, provided the SQL syntax is correct.

    Knowing your error message would help.

    --

    Adam

    Inspiring
    October 12, 2009

    Regarding,

    "However if your variable holds your entire SQL string, you probably DO NOT want the single quotes escaped across the board."

    The preservesinglequotes function is your friend here.