Coldfusion:执行包含cfqueryparam的动态查询

时间:2017-10-11 11:53:22

标签: coldfusion refactoring cfquery cfqueryparam

首先是代码。我正在制作一个查询结构:

<cfset myQueryStruct = { 
qone = "select * from t1 where column = <cfqueryparam cfsqltype='cf_sql_varchar' value='#arguments.a1#'>",
qtwo = "select * from t2 where column = <cfqueryparam cfsqltype='cf_sql_varchar' value='#arguments.a1#'>"
}>

我需要动态执行查询,如下所示:

<cfquery name="qName" datasource="#dsn#">
    #myQueryStruct[arguments.type]#
</cfquery>

但是我收到了一个错误:

Error Executing Database Query.
[Macromedia][SQLServer JDBC Driver][SQLServer]Incorrect syntax near '<'. 

似乎错误与查询中的“<cfqueryparam cfsqltype='cf_sql_varchar' value='#arguments.a1#'>”相关(“&lt;”)

我尝试使用evaluate()并收到此错误:

Invalid CFML construct found on line 1 at column 15.
ColdFusion was looking at the following text:

t1

我知道我们可以在<cfif>内使用<cfquery>阶梯来实现这一目标,但我的问题是,我们可以像我提到的那样做(我必须遗漏一些东西)或者在CFML中是不可能的?

2 个答案:

答案 0 :(得分:6)

问题是,您传递的字符串必须由ColdFusion处理。但你来不及了。 CF已经解析了模板,因此字符串保持未翻译状态,因此会抛出SQL错误。

我不确定,你想在这里完成什么,也许像这样的代码会起作用:

<cfscript>
dsn = "myDatabase";
criteria = "something";
myQueryStruct = {
    qone = "select * from t1 where column = ( :a1 ) ",
    qtwo = "select * from t2 where column = ( :a1 ) "
};

result1 = getQueryResult( queryString = myQueryStruct[ "qone" ], filterValue = criteria, dsn = dsn );
result2 = getQueryResult( queryString = myQueryStruct[ "qtwo" ], filterValue = criteria, dsn = dsn );

public function getQueryResult( queryString, filterValue, dsn ){
    var qry = new Query();
    var qryString = arguments.queryString;
    var queryResult = "";
    qry.setDatasource( arguments.dsn );
    qry.setSQl( qryString );
    qry.addParam( name="a1", value= arguments.filterValue, cfsqltype="cf_sql_varchar" ); 
    queryResult = qry.execute().getResult();
    return queryResult;
}
</cfscript>

答案 1 :(得分:0)

您可以先使用cfparam建立arguments.a1和数据类型,然后在查询中将变量引用为“#arguments.a1#”。它应该可以帮助您至少弄清楚它是否是导致问题的cfqueryparam标记。