我正在尝试遍历插入查询。我循环遍历返回结果在列表中的值。
<cfquery datasource="#OLMSdatasourceWrite#" result="myResult">
INSERT INTO OLMS_Data_RatioScenarios
(
OLMS_Account_ID,
OLMS_RatioScenario_Name
)
VALUES
(
<cfloop list="#AccountListWithSettings#" index="CurrentAccount">
(<cfqueryparam cfsqltype="cf_sql_numeric" value="#CurrentAccount#" maxlength="255">, <cfqueryparam cfsqltype="cf_sql_clob" value="#requestBody.value#" maxlength="255">)
<cfif CurrentAccount GT 1>
,
</cfif>
</cfloop>
)
</cfquery>
<cfoutput>Inserted ID is: #myResult.generatedkey#</cfoutput>
我在这里遇到的问题是它一直在最后一次迭代后加上一个“,”
VALUES ( ( (param 1) , (param 2) ) , ( (param 3) , (param 4) ) , ( (param 5) , (param 6) ) , )
我需要帮助找出 cfif 语句以防止这种情况(注意:如果我将 cfif 放在查询参数之上,它会开始循环,如 (,(param 1),(param 2),
最佳答案
您需要跟踪列表中的项目数并检查当前项目的位置是否小于列表的长度:
<cfset numItems = ListLen(AccountListWithSettings)>
<cfset i = 1>
<cfloop list="#AccountListWithSettings#" index="CurrentAccount">
<!--- Stuff inside of loop --->
<!--- ...and then --->
<cfif i lt numItems>
,
</cfif>
<cfset i++>
</cfloop>
更新,根据@Leigh 的评论:您也可以采用这种方法。我将其添加为第二种方法,因为即使它更简单,但我通常不会思考这个特定问题。每个人都有自己的。 :)
<cfset i = 1>
<cfloop list="#AccountListWithSettings#" index="CurrentAccount">
<cfif i gt 1>
,
</cfif>
<!--- Stuff inside of loop --->
<cfset i++>
</cfloop>
关于mysql - Coldfusion 循环插入查询值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42076240/