从cfquery记录集更新多行

时间:2013-11-15 18:19:41

标签: tsql coldfusion cfquery

当进入的数据来自CFQuery的结果时,有没有办法更新多行数据?目前这次运行<cfquery>多次。有没有办法在一个uqery操作中执行它?

<cfloop query=loc.fixItems>
    <cfset loc.count++>
    <cfset var categoryName = loc.fixItems.categoryName>


    <cfquery>
      update items
      set code = <cfqueryparam value="#code#">
      where id = <cfqueryparam value="#itemId#">
    </cfquery>
</cfloop>

这可能会多次运行并对服务器造成沉重负担。

2 个答案:

答案 0 :(得分:1)

您应该能够将循环放在cfquery

<cfquery>
  <cfloop query=loc.fixItems>
    <cfset loc.count++>
    <cfset var categoryName = loc.fixItems.categoryName>    
    update items
    set code = <cfqueryparam value="#code#"> -- code needs to be dynamic
    where id = <cfqueryparam value="#itemId#">; -- itemId needs to be dynamic
  </cfloop>
</cfquery>

答案 1 :(得分:0)

将数据加载到XML变量中并批量更新

<cfsavecontent variables="xmlData">
<ul class="xoxo">
   <cfoutput query="loc.fixItems">
     <li><b>#xmlformat(id)#</b> <code>#code#</code></li>
   </cfoutput>  
 </ul>
 </cfsavecontent>

 <!---
 <cfoutput>#xmlData#</cfoutput>
 --->

 <cfquery>
 DECLARE @xmlData xml = <cfqueryparam cfsqltype="CF_SQL_varchar" value="#xmlData#">


 ;
 WITH Data (id, code) AS (
    SELECT  tbl.Col.value('b[1]','varchar(20)') AS ID,
    tbl.Col.value('code[1]','varchar(50)') AS Code
    FROM    @xmlData.nodes('/ul/li') tbl(Col)
    )

 UPDATE items
   SET items.code = Data.code
 FROM items
 INNER JOIN Data
   ON items.id = Data.id    
 </cfquery>