Sql Server: Update XML Node value with new value in table

Introduction:  In this article I am going to share how to modify or we can say replace XML node/ attribute value with new value in sql server table based on condition. 


Implementation: Let’s create a table variable and insert some dummy xml data in table

DECLARE @Employee TABLE(empXML XML)

INSERT INTO @Employee VALUES('<ROOT><Employee Id="101" Name="Hrithik" City="Noida" Age="32" /></ROOT>')
INSERT INTO @Employee VALUES('<ROOT><Employee Id="102" Name="Ranbeer" City="Delhi" Age="25" /></ROOT>')
INSERT INTO @Employee VALUES('<ROOT><Employee Id="103" Name="Akshay" City="Mumbai" Age="56" /></ROOT>')
INSERT INTO @Employee VALUES('<ROOT><Employee Id="104" Name="Sidharth" City="Kolkata" Age="33" /></ROOT>')
INSERT INTO @Employee VALUES('<ROOT><Employee Id="105" Name="Randeep" City="Chennai" Age="29" /></ROOT>')
INSERT INTO @Employee VALUES('<ROOT><Employee Id="106" Name="Varun" City="Bengaluru" Age="30" /></ROOT>')

Check table data
SELECT * FROM @Employee

Update XML node value with new value in table in sql server

Suppose we want to update value of city node to "Pune" where Employee Id is 105
Then the query will be as following:

UPDATE @Employee SET
empXML.modify('replace value of (ROOT/Employee/@City)[1] with "Pune"')
WHERE empXML.value('(ROOT/Employee/@Id)[1]', 'INT') = 105

Check updated table data now
SELECT * FROM @Employee

Update XML node value with new value in table in sql server


   Now over to you:
A blog is nothing without reader's feedback and comments. So please provide your valuable feedback so that i can make this blog better and If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linkedin and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned and stay connected for more technical updates. 
Previous
Next Post »

If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily..