I want to perform an update on all the rows in an XML column in SQL Server 2008, replacing just a substring in a certain xml node. I'm new to XML DML / XQuery and all that and I just cannot figure out how to do it.
Example of XML in the column I want to update:
<d>
<p n="Richedit01" t="System.String">
<v>
<p> <img border="0" alt="Football4" src="/$-1/football4.jpg" /> </p>
</v>
</p>
</d>
I want to replace all occurances of the substring 'src="/$-1/' with 'src="/$-1/file/' in all rows.
Tried this but apparently there is no way that I can use the XPath replace function like this:
UPDATE Translation
SET ContentData.modify('replace value of (d/p[@t=''System.String'']/v)[1] with (d/p[@t=''System.String'']/v[replace(.,''src="/$-1/'',''src="/$-1/file/'')]) ')
Previously, a developer would update XML information by replacing the full XML document in the table column where it resided. But in the latest versions of SQL Server, we can use the XML modify() function in XQuery to update the XML data type column.
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.
You can use the SUBSTR operator to get a substring from a field. For example, to get bytes 3-7 of a field called MYNAME, use the expression SUBSTR(MYNAME,3,5). You can update part of a character field by concatenating the parts you want to stay intact with the new value.
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 think the easiest solution is to convert to another datatype that can accept replace (nvarchar(MAX) for example). Use the REPLACE function, and then convert it back to XML
Something like
UPDATE Translation SET
ContentData = CAST(REPLACE(CAST(ContentData AS NVARCHAR(MAX)), '/$-1/','/$-1/file/') AS XML)
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