开发者

Changing xml node value in SQL with xquery [SQL Server]

I have example XML in one of the table column:

<Root>
   <A>
      <C>c</C>
      <D>d</D>
   </A>
   <B>b</B>
</Root>

How can I replace value of A node into something like that:

<Root>
   <A>
      <E>e</E>
      <F>f</F>
   </A>
   <B>b</B>
</Root>

I tried the following solu开发者_运维问答tion

DECLARE @var varchar(100);
SET @var = '<E>e</E><F>f</F>'
SET @xml.modify('replace value of (/Root/A/text())[1] with sql:variable("@var")');

but it did not work...

regards


I do not think it is possible to use replace to replace nodes, only values. You can use delete and then insert instead.

declare @xml as xml = '
<Root>
  <A>
    <C>c</C>
    <D>d</D>
  </A>
  <B>b</B>
</Root>'

declare @var xml
set @var = '<E>e</E><F>f</F>'

set @xml.modify('delete /Root/A/*')
set @xml.modify('insert sql:variable("@var") into (/Root/A)[1]')

select @xml
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜