Use ampersand in CAST in SQL

edosoft picture edosoft · Jul 13, 2009 · Viewed 11.4k times · Source

The following code snippet on SQL server 2005 fails on the ampersand '&':

select cast('<name>Spolsky & Atwood</name>' as xml)

Does anyone know a workaround?

Longer explanation, I need to update some data in an XML column, and I'm using a search & replace type hack by casting the XML value to a varchar, doing the replace and updating the XML column with this cast.

Answer

John Saunders picture John Saunders · Jul 13, 2009

It's not valid XML. Use &amp;:

select cast('<name>Spolsky &amp; Atwood</name>' as xml)