条件Cfloop代码在第一次循环时放置AND

时间:2014-11-02 21:00:59

标签: coldfusion

使用以下查询,我在这里尝试做一个简单的案例,当遇到它的第一条记录应该基本上添加“AND”时,对于其余条件,我想添加OR < / p>

这是我的尝试

<cfif isDefined('age') and len(trim(age)) and age neq '-1'>
   <cfset age = trim(htmlEditFormat(lcase(age)))>
   <cfloop list="#age#" index="k">
       or age between #ListFirst(k,'-')# and #ListLast(k,'-')#
   </cfloop>
</cfif>

试图让它像这样工作

and (age between 18 and 20 
or age between 20 and 25 
or age between 25 and 30)

我没有得到添加括号和AND运算符的条件。

2 个答案:

答案 0 :(得分:2)

你可以做一些类似的事情,比如添加一个假语句然后根据需要循环其他所有内容

<cfif isDefined('age') and len(trim(age)) and age neq '-1'>
  <cfset age = trim(htmlEditFormat(lcase(age)))>
  AND (1 = 2 --always returns false
  <cfloop list="#age#" index="k">
    OR age between #ListFirst(k,'-')# and #ListLast(k,'-')#
  </cfloop>
  )
</cfif>

这就是你想要做的事情

<cfif isDefined('age') and len(trim(age)) and age neq '-1'>
  <cfset age = trim(htmlEditFormat(lcase(age)))>
  AND (
  <cfloop list="#age#" index="k">
    <cfif listFirst(age) NEQ k> OR </cfif> --if it's not the first iteration, add the OR
    age between #ListFirst(k,'-')# and #ListLast(k,'-')#
  </cfloop>
  )
</cfif>

答案 1 :(得分:1)

不需要if块的替代方案,适用于任何类型的循环:

<cfif isDefined('age') and len(trim(age)) and age neq '-1'>
   <cfset age = trim(htmlEditFormat(lcase(age)))>
   <cfset expressionSeparator = "">
   AND (
   <cfloop list="#age#" index="k">
       #expressionSeparator#
       age between #ListFirst(k,'-')# and #ListLast(k,'-')#
       <cfset expressionSeparator = " or ">
   </cfloop>
   )
</cfif>