我有一个像这样的列表 thing1,thing2,thing3。我想将它们插入到具有相同外键的查找表中。所以理想情况下它看起来像这样:
<cfquery datasource="#ds#" result="insert_things">
INSERT INTO lkp_things (foreign_key, thing) VALUES
(1, thing1), (1, thing2), (1, thing3)
</cfquery>
完成这个任务的唯一方法似乎是将列表变成一个查询,但我想知道,有没有更简单的方法?
这是我尝试过的:
<cfquery datasource="#ds#" result="insert_things">
INSERT INTO lkp_things (foreign_key, thing) VALUES
<cfloop list="#things#" index="thing">
(#id#,#thing#)<cfif ?????? NEQ len(#things#)>,</cfif>
</cfloop>
</cfquery>
我听说不能在 cfquery 中执行 cfloop,但我什至不确定这是不是真的,因为我不能在 VALUES 中有尾随逗号,而且我不确定如何在 cfloop 中说“当前迭代次数”。如果我将列表转换为查询,那么我可以执行 currentRow,但同样,在我完成所有这些之前,我想知道是否有更简单的方法来完成此操作。
此外,我使用的是 CF 8 和 sql server '08 编辑:抱歉,我实际上使用的是 2000。
最佳答案
更新:
最终,这里真正的问题是,只有 SQL Server 2008+ 支持使用单个 VALUES
子句插入多组值的功能,而 OP 使用的是 2000。所以他们选择了select / union all approach相反。
(从评论中扩展)
当然,您可以在 cfquery
中循环。所有 cfml 代码首先在 CF 服务器上处理。然后将生成的 SQL 字符串发送到数据库执行。只要您的 CF 代码生成有效的 SQL 语句,您就可以做任何您想做的事 :) 是否应该是一个不同的问题,但这种循环非常好。
回到您的问题,只需切换到 from/to
循环并使用 getToken(list, index)
等列表函数来获取各个元素(请参阅Matt's example ) 或改用数组。显然,您还应该先验证列表是否为空。我个人的偏好是数组。未经测试,但像这样:
<cfset thingArray = listToArray(things, ",")>
<cfquery datasource="#ds#" result="insert_things">
INSERT INTO lkp_things (foreign_key, thing) VALUES
<cfloop from="1" to="#arrayLen(thingArray)#" index="x">
<cfif x gt 1>,</cfif>
(
<!--- Note: Replace cfsqltype="..." with correct type --->
<cfqueryparam value="#id#" cfsqltype="...">
, <cfqueryparam value="#thingArray[x]#" cfsqltype="...">
)
</cfloop>
</cfquery>
话虽如此,您的#thing#
列表的来源是什么?如果这些值存在于数据库表中,您可以使用 SELECT
语句直接插入它们,而不是循环:
INSERT INTO lkp_things (foreign_key, thing)
SELECT <cfqueryparam value="#id#" cfsqltype="...">, thing
FROM ThingTable
WHERE thing IN
(
<cfqueryparam value="#thingList#" list="true" cfsqltype="...">
)
关于sql - ColdFusion:如何在一次插入中插入带有静态外键的列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19591652/