Can I do a find/replace in t-sql? Can I do a find/replace in t-sql? xml xml

Can I do a find/replace in t-sql?


For anything real, I'd go with xpaths, but sometimes you just need a quick and dirty solution:

You can use CAST to turn that xml column into a regular varchar, and then do your normal replace.

UPDATE xmlTable SET xmlCol = REPLACE( CAST( xmlCol as varchar(max) ), '[search]', '[replace]')

That same technique also makes searching XML a snap when you need to just run a quick query to find something, and don't want to deal with xpaths.

SELECT * FROM xmlTable WHERE CAST( xmlCol as varchar(max) ) LIKE '%found it!%'

Edit: Just want to update this a bit, if you get a message along the lines of Conversion of one or more characters from XML to target collation impossible, then you only need to use nvarchar which supports unicode.

CAST( xmlCol as nvarchar(max) )


To find a content in an XML column, look into the exist() method, as described in MSDN here.

SELECT * FROM TableWHERE XMLColumn.exist('/Root/MyElement') = 1

...to replace, use the modify() method, as described here.

SET XMLColumn.modify('  replace value of (/Root/MyElement/text())[1]  with "new value"')

..all assuming SqlServer 2005 or 2008. This is based on XPath, which you'll need to know.


update my_tableset xml_column = replace(xml_column, "old  value", "new value")