#SQL: Update xml field from value from other table

We are going to update Title field in XML below. Assume we have incorrect values there in our Library table. We will find the correct values by using Title field from AllBooks table.

<Book xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
 <Title>Incorrect Title</Title>
</Book>
UPDATE Library SET info.modify('replace value of (/Book/Title/text())[1] with sql:column("Title")')
FROM Library 
LEFT OUTER JOIN AllBooks ON Library.BookID=AllBooks .ID
WHERE info.value('data((/Book/Title)[1])','nvarchar(max)') like 'Incorrect Title%'

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s