Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query data in XML column in SQL Server

I have data like this in an xml column:

<product>
   <productID>1</productID>
   <productname>tea</productname>
</product>
<product>
   <productID>2</productID>
   <productname>coffee</productname>
</product>

I want to change the value of productname to green tea where productID = 2.

I am using:

UPDATE [dbo].ProductDocs
SET ProductDoc.modify('replace value of (/Product/ProductName)[2] with "NewName"')

But here it will always change the value in second product. Please tell me how to query with productID.

like image 531
Madhav Avatar asked May 31 '26 11:05

Madhav


1 Answers

Use predicate expression to filter product element by productID value like so :

UPDATE [dbo].ProductDocs
SET ProductDoc.modify('
    replace value of (/product[productID=2]/productname/text())[1] with "NewName"
')

Also notice that, as mentioned in the other answer, XML and XPath/XQuery are case-sensitive.

like image 62
har07 Avatar answered Jun 03 '26 01:06

har07



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!