I basically have an xml column, and I need to find and replace one tag value in each record.
3 Answers
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) )

- 1,583
- 18
- 22
-
@Cory-Mawhorter You mentioned XPath would be "better". How would you use XPath to change something in the XML column? – Arminder Dahul Oct 09 '15 at 09:05
-
@ArminderDahul It has been a while but I think you can do it like `set xmlCol.nodes('/somenode/someothernode[@id=sql:variable("@somevar")]/text') = 'blah'`. Not sure. Michael's answer might get you started. – Cory Mawhorter Oct 10 '15 at 18:18
To find a content in an XML column, look into the exist() method, as described in MSDN here.
SELECT * FROM Table
WHERE 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.

- 59,888
- 27
- 145
- 179
update my_table
set xml_column = replace(xml_column, "old value", "new value")

- 18,340
- 6
- 53
- 62
-
4"Argument data type xml is invalid for argument 1 of replace fuction" – Phil Gan Jul 28 '10 at 13:33