Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server FOR XML Enclosing Element?

Using SQL Server 2008, I have a query that emits a result set using FOR XML. Right now it is a non-compliant fragment.

How can I wrap my result XML in an enclosing element and then put a simple XML declaration on top with a single schema/namespace reference to make the output compliant?

Thanks.

like image 671
Snowy Avatar asked Sep 10 '26 10:09

Snowy


2 Answers

It is not possible to have the XML processing instruction in a XML datatype in SQL Server.

See Limitations of the XML Data Type

This code

declare @XML xml =  
  '<?xml version="1.0"?>
   <root>Value</root>'

select @XML

Has the output

<root>Value</root>

You can build the XML as a string with the XML processing instruction in place.

declare @XML xml = '<root>Value</root>'
declare @XMLStr nvarchar(max) = '<?xml version="1.0"?>'
  
set @XMLStr = @XMLStr + cast(@XML as nvarchar(max))

select @XMLStr

Output

--------------------------------------------------------------------------
<?xml version="1.0"?><root>Value</root>
like image 57
Mikael Eriksson Avatar answered Sep 13 '26 00:09

Mikael Eriksson


Add "WITH XMLNAMESPACES" to the beginning and a ROOT() to the FOR XML clause:

WITH XMLNAMESPACES ( DEFAULT 'http://namespace_uri_here' )
SELECT * 
FROM TABLE
FOR XML AUTO, ROOT('TopLevel')
like image 36
jfollas Avatar answered Sep 12 '26 23:09

jfollas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!