SQL server insert data from table into an XML variable

erikkallen picture erikkallen · Nov 20, 2009 · Viewed 12.9k times · Source

How can I insert a whole bunch of rows into an XML variable without using a cursor? I know I can do

SET @errors.modify('insert <error>{ sql:variable("@text") }</error> as last into /errors[1]')

to insert the value of a variable, but I want to basically do

SET @errors.modify(SELECT 'insert <error>{ sql:column("text") }</error>' FROM table)

which, of course, isn't legal syntax.

Edit: Obviously my question wasn't clear. What I want is to be able to do like this:

CREATE TABLE my_table(text nvarchar(50))
INSERT INTO my_table VALUES('Message 2')
INSERT INTO my_table VALUES('Message 3')

DECLARE @errors xml
SET @errors = '<errors><error>Message 1</error></errors>'

SET @errors.modify('INSERT EVERYTHING FROM my_table MAGIC STATEMENT')

And after running this code, @errors should contain

<errors>
  <error>Message 1</error>
  <error>Message 2</error>
  <error>Message 3</error>
</errors>

Answer

Mike Knox picture Mike Knox · Jun 27, 2010

Isn't this simpler?

set ErrorXML=(SELECT * from #MyTable FOR XML AUTO)