Updating SQL Server XML node

為{幸葍}努か 提交于 2019-12-02 10:06:40

问题


I am trying to update a node Qty of my XML which is stored inside a SQL Server XML column, no error occurred but my field did not got updated.

Please advice. Thanks.

XML data copied from SQL Server xml column:

<ArrayOfCampaignVoucher xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
 <CampaignVoucher>
   <VouCode>Vouch002</VouCode>
   <Qty>4</Qty>
</CampaignVoucher>
<CampaignVoucher xsi:nil="true" /></ArrayOfCampaignVoucher>

Stored procedure:

USE [c1]
GO
/****** Object:  StoredProcedure [dbo].[Campaign_InsertRewardsVoucher]    Script Date: 10/22/2011 23:33:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
*/
ALTER PROCEDURE [dbo].[Campaign_InsertRewardsVoucher]  

    @voucherXML         XML, -- @voucherXML is the XML pass from my SQL server 

AS  
BEGIN

declare @changedVal int
set @changedVal = 4 

UPDATE  [Customers] 
SET  voucherXML.modify('replace value of (/CampaignVoucher/Qty/text())[1] with "0"') 
WHERE  voucherXML.value('(/CampaignVoucher/Qty)[1]', 'int') = @changedVal 


END

回答1:


You're ignoring the root level node <ArrayOfCampaignVoucher> - try this:

UPDATE 
   dbo.[Customers] 
SET 
   voucherXML.modify('replace value of (/ArrayOfCampaignVoucher/CampaignVoucher/Qty/text())[1] with "0"') 
WHERE  
   voucherXML.value('(/ArrayOfCampaignVoucher/CampaignVoucher/Qty)[1]', 'int') = @changedVal 



回答2:


Or, you could do the following, assuming SQL Server supports the descendent-or-self axis, and assuming that Qty has no other ancestors:

UPDATE dbo.[Customers] SET voucherXML.modify('replace value of (//Qty/text())[1] with "0"') WHERE
voucherXML.value('(//Qty)[1]', 'int') = @changedVal

But it seems like you have multiple CampaignVoucher nodes per Array, and that you wouldn't want to wholesale replace the first instance of a value with a new value. Instead, wouldn't you want to restrict the update to a voucher with a specific VouCode?



来源:https://stackoverflow.com/questions/7861378/updating-sql-server-xml-node

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!