3

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.

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

First thing first, XML is case-sensitive and so are the XQuery expressions.

Now you could do this.

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

2 Comments

Agreed about case-sensitivity. But the XQuery will trigger 'syntax-error' because /[some_expression] is not valid expression. Furthermore, productID/@Value references value attribute of productID element, there is no such attribute in the OP's XML.
@har07 yeah.. I thought it was a value, fixed it now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.