ColdFusion在基于脚本的cfc函数中使用if条件

时间:2019-02-14 15:11:13

标签: coldfusion cfml

我正在尝试使自己的cfscript更好,但无法弄清楚这一点。在基于标签的CFC中,我可以执行以下操作:

<cffunction name="querySd" access="public" returnType="query" output="false">
  <cfargument name="sd_id" type="numeric" required="No"/>
  <cfargument name="sd_code" type="string" required="No"/>
  <cfquery name="LOCAL.qrySd" datasource="#variables.dsn#">
    SELECT sd_id, sd_code, sd_active, sd_expires, sd_added, sd_dla
     FROM sd 
    WHERE 0=0
     <cfif isDefined("ARGUMENTS.sd_id")>
       AND sd_id = <cfqueryparam cfsqltype="CF_SQL_INTEGER" value="#ARGUMENTS.sd_id#"/>
     </cfif>
     <cfif isDefined("ARGUMENTS.sd_code")>
      AND sd_code = <cfqueryparam cfsqltype="CF_SQL_VARCHAR" value="#ARGUMENTS.sd_code#" maxlength="20"/>
     </cfif>
    </cfquery>
  <cfreturn LOCAL.qrySd>
</cffunction>

但是,在cfscript中尝试类似的方法会引发错误:

public query function querySd( numeric sd_id, string sd_code ){
  local.querySd = new Query(datasource = variables.dsn);
  if( isDefined('arguments.sd_id') ){
    local.querySd.addParam( name = 'sdid', value = arguments.sd_id, cfsqltype = 'cf_sql_int');
  };
  if( isDefined('arguments.sd_code') ){
    local.querySd.addParam( name = 'sdcode', value = arguments.sd_code, cfsqltype = 'cf_sql_varchar', maxlength = '20');
  };

 local.querySd.setSql('
            SELECT sd_id, sd_code, sd_active, sd_expires, sd_added, sd_dla
              FROM sd
             WHERE 0 = 0
             if( isDefined('arguments.sd_id') ){
                 AND sd_id = :sdid 
             };
             if( isDefined('arguments.sd_code') ){
                 AND sd_code = :sdcode 
             };
        ');
local.qrySd = local.querySd.execute().getResult();

在cfc中基于cfscript的查询中使用可选参数的正确方法是什么?

3 个答案:

答案 0 :(得分:4)

您可以将查询的一部分放在变量中,并在查询字符串中使用它。

local.queryPart = '';
if( isDefined('arguments.sd_id') ){
    local.queryPart &= ' AND sd_id = :sdid ';
};
if( isDefined('arguments.sd_code') ){
    local.queryPart &= ' AND sd_code = :sdcode ';
};
local.querySd.setSql('
    SELECT sd_id, sd_code, sd_active, sd_expires, sd_added, sd_dla
    FROM sd
    WHERE 0 = 0
    #local.queryPart#
');

答案 1 :(得分:3)

正如其他人所说,根据您使用的CF版本,我会在queryExecute()上使用new Query()。原因很多,而这本身就是一个完全其他的话题。

无论如何,现在我有一点时间,为了完整起见,我整理了一个queryExecute()的示例。 注意:我在这里使用针对模拟数据的查询查询。真正的查询将使用实际的数据源。

<cfscript>
public Query function querySd2 ( Numeric sd_id, String sd_code ) {
    // This is my fake query data, thanks to Mockaroo.
    local.sd = queryNew("sd_id,sd_code,sd_active,sd_expires,sd_added,sd_dla",
    "integer,varchar,bit,date,date,varchar",
    [ 
        { "sd_id":1,"sd_code":"DontPickMe","sd_active":true,"sd_expires":"2019-01-04","sd_added":"2018-05-07","sd_dla":"2M66CAf3" } ,
        { "sd_id":2,"sd_code":"PickMe","sd_active":true,"sd_expires":"2018-03-03","sd_added":"2018-08-18","sd_dla":"8FW4HRm8" } ,
        { "sd_id":3,"sd_code":"DontPickMe","sd_active":true,"sd_expires":"2019-01-01","sd_added":"2018-10-28","sd_dla":"4F6kBUm2" } ,
        { "sd_id":4,"sd_code":"PickMe","sd_active":false,"sd_expires":"2018-10-28","sd_added":"2018-08-22","sd_dla":"2NSlNLr8" } ,
        { "sd_id":5,"sd_code":"DontPickMe","sd_active":false,"sd_expires":"2018-03-07","sd_added":"2019-02-09","sd_dla":"8T0cWQc2" }
    ]);
    ////////////////

    local.sqlWhere = "1=1" ; // This is our default WHERE condition.
    local.qryParams  = {} ;  // queryExecute expects a struct of params. Or an array.

    // First, I check that the given args have a length, then create both 
    // the SQL and the param. Also "?." is the safe-navigation operator, added
    // in CF2016. https://helpx.adobe.com/coldfusion/using/language-enhancements.html
    if( len(trim(arguments?.sd_id)) ) {
        sqlWHERE &= " AND sd_id = :sdid" ;  // This is our SQL string. 
        qryParams.sdid = { value:arguments.sd_id, cfsqltype:"cf_sql_integer" } ;
    }

    if( len(trim(arguments?.sd_code)) ) {
        sqlWHERE &= " AND sd_code = :sdcode" ;
        qryParams.sdcode = { value:arguments.sd_code, cfsqltype:"cf_sql_varchar", maxlength:"20" }  ;
    }

    //writeDump(sqlWhere) ;

    // https://cfdocs.org/queryexecute
    local.qrySd = queryExecute( 
          "SELECT sd_id, sd_code, sd_active, sd_expires, sd_added, sd_dla FROM sd WHERE #sqlWhere#" 
        , qryParams 
        , { dbtype="query"} //datasource="dsn" } // Replace dbtype with datasource.
    ) ;
    return qrySd ;  // return our query object.
}

// TESTS
tests = [
    {qry:querySd2(2,"PickMe")         , label:"Results from query"                 , retval:querySd2(2,"PickMe").sd_expires } ,
    {qry:querySd2(1,"PickMe")         , label:"No Results from query"              , retval:querySd2(1,"PickMe").sd_expires } ,
    {qry:querySd2(1)                  , label:"No Param2"                          , retval:querySd2(1).sd_expires } ,
    {qry:querySd2(sd_code = "PickMe") , label:"No Param1 (CF2018+ (named params))" , retval:querySd2(sd_code = "PickMe").sd_expires } ,
    {qry:querySd2()                   , label:"No Params"                          , retval:querySd2().sd_expires } ,
    {qry:querySd2(1," ")              , label:"Edge. Empty string."                , retval:querySd2(1," ").sd_expires } 
] ;
//// Note that the above retval:querySd2().sd_expires only outputs one row. Loop
//// through the results themselves to output the multiple rows. 

writeDump(tests) ;
</cfscript>

https://cffiddle.org/app/file?filepath=32c93137-adb1-4f58-8ed4-21bb9e5212b2/ee3d9cac-e25e-46ca-8eec-f4ac8ddd4b41/4d295400-65fa-4b76-a889-a97a805409ea.cfm

注意: queryExecute()已添加到CF11中。 CF2016中添加了安全导航(?.)。

编辑:我将Mockaroo数据更改为静态查询数据。显然,您可以非常快速地运行Mockaroo数据。 :-)

答案 2 :(得分:2)

您还可以使用三元运算符:

local.querySd.setSql('
        SELECT sd_id, sd_code, sd_active, sd_expires, sd_added, sd_dla
          FROM sd
         WHERE 0 = 0
         # !isNull( arguments.sd_id ) ? ' AND sd_id = :sdid' : '' #
         # !isNull( arguments.sd_code ) ? ' AND sd_code = :sdcode' : '' #
    ');

我个人认为这更具可读性。