2011-10-23 57 views
2

我想更新XML中存儲在SQL Server XML列中的一個節點,如果我的XML位於XML元素中,但是現在我以某種方式需要將其更改爲XML屬性,顯然該行在更改後變爲無效。在SQL Server XML列中更新XML屬性

作品爲的XMLElement:

UPDATE [Customers] 
SET voucherXML.modify('replace value of (/ArrayOfCampaignVoucher/CampaignVoucher/Qty/text())[1] with "50"') 
WHERE voucherXML.value('(/ArrayOfCampaignVoucher/CampaignVoucher/VouCode)[1]', 'nvarchar(50)') = @VoucherCode 

我試圖改變這樣的說法,但沒有運氣,沒有錯誤,但QTY值沒有得到改變的@NewQuantity值:

UPDATE [Customers] 
     SET voucherXML='<ArrayOfCampaignVoucher xmlns:xsd="http://www.w3.org/2001/XMLSchema" Qty="' + CAST(@NewQuantity AS NVARCHAR(16)) + '" />' 
    WHERE voucherXML.value('(/CampaignVoucher/VouCode)[1]', 'nvarchar(50)') = @VoucherCode 

這是我的XML在SQL Server XML列中的外觀:

<ArrayOfCampaignVoucher xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
    <CampaignVoucher VouCode="Vouc001" Qty="16" /> 
    <CampaignVoucher VouCode="Vouc002" Qty="18" /> 
    <CampaignVoucher xsi:nil="true" /> 
</ArrayOfCampaignVoucher> 
+0

刪除了'asp.net','c#'和'vb.net'標記 - 與任何這些技術無關,真的.. –

回答

7

您應該使用XQuery函數 - 不串起來的這樣的XML ....

試試這個:

DECLARE @newquantity INT = 55 

UPDATE dbo.Customers 
SET voucherXML.modify('replace value of (/ArrayOfCampaignVoucher/CampaignVoucher[@VouCode="Vouc002"]/@Qty)[1] with sql:variable("@NewQuantity") ') 

這對我的作品 - 節點與VouCode="Vouc002"Qty屬性被更新爲價值我在一個SQL變量之前定義

更新:插入新的<CampaignVoucher>項,使用XQuery這樣的事情:

UPDATE dbo.Customers 
SET voucherXML.modify('insert <CampaignVoucher VouCode="Vouc003" Qty="42" /> 
         as last into (/ArrayOfCampaignVoucher)[1]') 
+0

感謝您的幫助,請您提供一個示例插入一個新的屬性:添加VouCode和Quantity的另一行,以及刪除基於VouCode的屬性。我正嘗試尋找有關這方面的教程,但運氣不大。謝謝! – k80sg

+0

@ user415795:查看「15秒鐘」這個由三部分組成的系列文章:http://www.15seconds.com/issue/050803.htm –