Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update substring in XML column SQL Server 2008

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>
      &lt;p&gt; &lt;img border="0" alt="Football4" src="/$-1/football4.jpg" /&gt; &lt;/p&gt;
    </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/'')]) ') 
like image 661
Kberg Avatar asked Mar 27 '12 07:03

Kberg


People also ask

How to update XML column value in SQL Server?

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.

How to update XML data in SQL table?

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 substring of a column in SQL?

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.

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.


Video Answer


1 Answers

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)
like image 147
James Osborn Avatar answered Oct 19 '22 20:10

James Osborn