SQL Server XML替换属性中的值

时间:2011-09-29 11:06:39

标签: xml sql-server-2008 replace

我想替换XML中属性中的值。该属性在xml中多次出现。我怎样才能一次性替换这些

我的xml会隐藏下面的内容:

 <Example>
  <A>
   <B Type = "x">qqq</B>
   <B Type = "x">www</B>
  </A>
  <C>
   <D Type = "x">aaa</D>
   <D Type = "x">uuu</D>
  </C>
 </Example>

我想用y

替换所有x

2 个答案:

答案 0 :(得分:1)

您无法使用replace value of (XML DML)一次替换所有内容。你必须循环。

declare @xml xml = '
<Example>
  <A>
   <B Type = "x">qqq</B>
   <B Type = "x">www</B>
  </A>
  <C>
   <D Type = "x">aaa</D>
   <D Type = "x">uuu</D>
  </C>
 </Example>
'

while (select @xml.exist('//*[@Type = "x"]')) = 1
begin
  set @xml.modify('replace value of (//*[@Type = "x"]/@Type)[1] with "y"')
end

select @xml

结果:

<Example>
  <A>
    <B Type="y">qqq</B>
    <B Type="y">www</B>
  </A>
  <C>
    <D Type="y">aaa</D>
    <D Type="y">uuu</D>
  </C>
</Example>

<强>更新

将值x和z替换为y:

while (select @xml.exist('//*[@Type = ("x","z")]')) = 1
begin
  set @xml.modify('replace value of (//*[@Type = ("x","z")]/@Type)[1] with "y"')
end

用y代替所有值:

while (select @xml.exist('//*[@Type != "y"]')) = 1
begin
  set @xml.modify('replace value of (//*[@Type != "y"]/@Type)[1] with "y"')
end

答案 1 :(得分:0)

You can try the following. Here ns2zarejestrujStanZgodyAsync is main node and I have updated the value of idSystemy from 13 to 38.

UPDATE @t
SET yourXML.modify('replace value of 
(/ns2zarejestrujStanZgodyAsync/rejestrujStanZgody/idSystemy/text())[1] with ("38")')

You can check for demo here- XML Node Update