Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TSQL: How can I update the value of an xml tag with the value of an xml tag from another related table?

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
like image 765
halfjust Avatar asked Jun 16 '10 03:06

halfjust


People also ask

How do I change the value of an XML column in SQL?

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.

How do you update a selected value in SQL?

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.

How edit XML in SQL?

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.


2 Answers

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
like image 98
Adam Wenger Avatar answered Sep 25 '22 14:09

Adam Wenger


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.

like image 26
marc_s Avatar answered Sep 23 '22 14:09

marc_s