0

我正在尝试使用更新 SQL Server 表中的 XML 列

XML.modify replace value of (XML DML)

使用下面的 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>

请指教。

谢谢!

4

2 回答 2

1

您必须使用循环并一次更新一个值。

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

SQL小提琴

更新表中 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小提琴

于 2014-01-29T06:44:15.623 回答
0

如果您需要将一个常量字符串替换为另一个字符串,我建议您使用REPLACE函数并在字符串上执行它。

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

在许多情况下,使用 xml 样式执行此操作要容易得多。

于 2014-01-29T01:35:20.293 回答