How can I update the value of an xml tag with the value of an xml tag from another related table?
something like this:
UPDATE v2
SET
[xml].modify ('replace value of (//TAG1/text())[1]
with "CAST(v1.[xml].query(''//TAG2'') AS NVARCHAR(MAX))"')
FROM
table2 v2,
table1 v1
WHERE
v2.id = v1.id
To update data in an XML column, use the SQL UPDATE statement. Include a WHERE clause when you want to update specific rows. The entire column value will be replaced. The input to the XML column must be a well-formed XML document.
The UPDATE from SELECT query structure is the main technique for performing these updates. An UPDATE query is used to change an existing row or rows in the database. UPDATE queries can change all tables' rows, or we can limit the update statement affects for certain rows with the help of the WHERE clause.
modify() Method (xml Data Type) Use this method to modify the content of an xml type variable or column. This method takes an XML DML statement to insert, update, or delete nodes from XML data. The modify() method of the xml data type can only be used in the SET clause of an UPDATE statement.
I'm pretty late to this question, but if you're looking to "mass update" an XML column in the future, and you are in SQL 2005+, you can use a CTE to accomplish this:
WITH NewXmlData AS
(
SELECT v2.Id AS id
, CAST(v1.[xml].query('//TAG2') AS NVARCHAR(MAX)) AS NewValue
FROM table2 AS v2
INNER JOIN table1 AS v1 ON v2.id = v1.id
)
UPDATE v2
SET [xml].modify ('replace value of (//TAG1/text())[1]
with sql:column("NewXmlData.NewValue")')
FROM table2 AS v2
INNER JOIN NewXmlData AS nxd ON v2.id = nxd.id
I don't think you can do this in a single step - but you can do it in two steps, if you're on SQL Server 2008:
DECLARE @NewValue NVARCHAR(50)
SELECT @NewValue = [xml].value('(//TAG2)[1]', 'NVARCHAR(50)')
FROM dbo.v1
WHERE id = 1
UPDATE dbo.v2
SET [xml].modify('replace value of (//TAG1/text())[1] with sql:variable("@NewValue")')
WHERE id = 1
The ability to specify a sql:variable
in your replace value of
XQuery is a new feature in SQL Server 2008 - so if you're stuck on 2005, this won't work, unfortunately.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With