How to update xml node value based on another node value in SQL Server

1.3k views Asked by At

I have the following employees XML in "Test" table

<employees>
   <employee>
     <id>1</id>
     <name>John doe 1</name>
   </employee>
   <employee>
     <id>2</id>
     <name>John doe 2</name>
   </employee>
   <employee>
     <id>3</id>
     <name>John doe 3</name>
   </employee>
</employees>

I have to update the employee name whose id is 3. I am updating the following way.

update Test
set employeesXML.modify('replace value of (/employees/employee/name/text())[1]
with "xyz"')
where employeesXML.exist(N'/employees/employee/id[text()="3"]')

It updates the employee name with id 1 but if I don't specify the node index it throws an error.

How do I replace the value of a node based on the value of another node?

1

There are 1 answers

0
Paweł Dyl On BEST ANSWER

To select node with id, use following:

DECLARE @xml xml = '<employees>
   <employee>
     <id>1</id>
     <name>John doe 1</name>
   </employee>
   <employee>
     <id>2</id>
     <name>John doe 2</name>
   </employee>
   <employee>
     <id>3</id>
     <name>John doe 3</name>
   </employee>
</employees>'

SELECT @xml.value('(//employee[id=3]/name)[1]', 'nvarchar(max)')

To modify, use:

SET @xml.modify('replace value of (//employee[id=3]/name/text())[1] with "xyz"')