rysiard
rysiard

Reputation: 77

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 solution

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

Upvotes: 0

Views: 1729

Answers (1)

Mikael Eriksson
Mikael Eriksson

Reputation: 138960

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

Upvotes: 1

Related Questions