cfquery to queryExecute: if inside SQL 字符串

cfquery to queryExecute: if inside SQL string

什么是最好的方法来完成我在<cfquery>甚至在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>

希望我已经解释清楚了...

您必须构建 SQL 字符串。同样值得传递参数值,这样您就可以免受 SQL 注入。类似于:

<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>

或者,您可以使用位置参数。

<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>

这是标签优于脚本的时代之一。