简体   繁体   English

在SQL Server XML列中更新XML属性

[英]Updating XML attribute in SQL Server XML column

I am trying to update a node of in my XML which is stored in a SQL Server XML column, the line below works if my XML is in a XML element but now I somehow need to change it to XML attributes, apparently the line becomes invalid after the change. 我正在尝试更新存储在SQL Server XML列中的XML中的一个节点,如果我的XML在XML元素中,则下面的行有效,但是现在我需要以某种方式将其更改为XML属性,显然该行变得无效更改后。

Works for XMLElement: 适用于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 

I tried changing the statement like this but no luck, no errors but QTY values doesn't get change to the value of @NewQuantity : 我试图像这样更改语句,但是没有运气,没有错误,但是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 

This is how my XML looks in the SQL Server XML column: 这是我的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>

You should use the XQuery functions - not string together your XML like this.... 您应该使用XQuery函数-不要像这样将XML串在一起。

Try this instead: 试试这个:

DECLARE @newquantity INT = 55

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

This works for me - the Qty attribute of the node with VouCode="Vouc002" gets updated to the value I defined before in a SQL variable 这对我VouCode="Vouc002" -具有VouCode="Vouc002"的节点的Qty属性更新为我之前在SQL变量中定义的值

Update: to insert a new <CampaignVoucher> entry, use XQuery something like this: 更新:要插入新的<CampaignVoucher>条目,请使用XQuery如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM