2014-01-28 37 views
0

我試圖使用如何在SQL Server表

XML.modify replace value of (XML DML) 

隨着XML以下示例更新在SQL Server表中的XML列的XML字段修改XML屬性,是有一種方法,我可以取代所有vendorId價值1到另一個值?從http://technet.microsoft.com/en-us/library/ms190675.aspx的文檔看來,我需要爲它指定記錄索引。但在我的情況下,會有在XML中多條記錄,我不知道它會在秩序。

<LineItems> 
    <LineItem productId="48" invId="1573" quantity="1" id="1" vendorId="1022" price="1350.0000" cost="450.0000" discount="0" acqu="2" /> 
    <LineItem productId="1" invId="0" quantity="1" id="2" vendorId="1" price="400" cost="0" discount="0" /> 
    <LineItem productId="46" invId="1574" quantity="1" id="3" vendorId="1022" price="789.0000" cost="263.0000" discount="0" acqu="4" /> 
    <LineItem productId="1" invId="0" quantity="1" id="4" vendorId="1" price="300" cost="0" discount="0" /> 
</LineItems> 

請指點。

謝謝!

回答

1

您必須一次使用循環並更新一個值。

while @XML.exist('/LineItems/LineItem[@vendorId = "1"]') = 1 
    set @XML.modify('replace value of (/LineItems/LineItem[@vendorId = "1"]/@vendorId)[1] with "2"') 

SQL Fiddle

,表中的更新一個XML列是這樣一個版本。

while exists(
      select * from T 
      where T.XMLColumn.exist('/LineItems/LineItem[@vendorId = "1"]') = 1 
        --and [some other condition] 
      ) 
begin 
    update T 
    set XMLColumn.modify('replace value of (/LineItems/LineItem[@vendorId = "1"]/@vendorId)[1] with "2"') 
    where T.XMLColumn.exist('/LineItems/LineItem[@vendorId = "1"]') = 1 
     --and [some other condition] 
end 

SQL Fiddle

+0

我將如何使用這一個UPDATE語句? – Ganesh

+0

@Ganesh我已更新回答 –

+0

謝謝@Mikael。這對我的情況非常有效,儘管我不確定這是否是頻繁更新的優化方法。 – Ganesh

0

如果您需要將常量字符串替換爲另一個字符串,我建議您使用REPLACE函數並在字符串中執行它。

DECLARE @XML XML /*your xml value*/ 
SELECT REPLACE(CONVERT(NVARCHAR(MAX),@XML),'vendor="1"','"vendor="2"') 

在許多情況下,以xml樣式進行操作要容易得多。