coldfusioncfmlluceecfexecute

cfquery to queryExecute: if inside SQL string


what is the best way to do what I did in <cfquery> even in queryExecute

cfquery

<cfquery name="qry">
    SELECT * FROM tbl_products
    WHERE filed1 = 1

    <cfif structKeyExists(URL, "test")>
        AND filed2 = 2
    </cfif>

    ORDER BY id DESC
</cfquery>

cfexecute

<cfscript>

    sql = "
        SELECT * FROM tbl_products
        WHERE filed1 = 1
        ORDER BY id DESC
    ";

    if (structKeyExists(URL, "test")){
        sql = "
            SELECT * FROM tbl_products
            WHERE filed1 = 1
            AND filed2 = 2
            ORDER BY id DESC
        ";
    }

    qry = queryExecute(
        sql = sql
    );

</cfscript>

I hope I've explained myself well...


Solution

  • You have to build up the SQL string. Also well worth passing in the param values, so that you are protected from SQL injection. Something like:

    <cfscript>
    params = {};
    
    sql = "
        SELECT * FROM tbl_products
        WHERE filed1 = :filed1 
    ";
    params["filed1"] = 1;
    
    if (structKeyExists(URL, "test")){
        sql &= "AND filed2 = :filed2 ";
        params["filed2"] = 2;
    }
    
    sql &= "ORDER BY id DESC";
    
    queryExecute(sql, params);
    </cfscript>
    

    Alternatively, you can use positional parameters.

    <cfscript>
    params = [];
    
    sql = "
        SELECT * FROM tbl_products
        WHERE filed1 = ?
    ";
    arrayAppend(params, 1);
    
    if (structKeyExists(URL, "test")){
        sql &= "AND filed2 = ? ";
        arrayAppend(params, 2);
    }
    
    sql &= "ORDER BY id DESC";
    
    queryExecute(sql, params);
    </cfscript>
    

    This is one of the times where tags is better than script.