Question : CDATA tags appearing incorrectly in XML output using FOR XML PATH

I need to output XML from a stored procedure on SQL 2008.  The fields each need to be wrapped in the CDATA tag (requirement by our customer receiving the data).  So I've written the following SQL.

select  '<![CDATA[' + c.FirstName + ' ' + c.LastName + ']]>' [name]
from dbo.Customer c
where c.Customer_id = @CustomerId
FOR XML PATH ('customer'), ROOT('customers')

The output doesn't come out exactly as expected though.  I am new to outputting XML from SQL however.  So for my output, though it loads in the SQL XML viewer, it looks like this:

<customers>
  <customer>
    <name>&lt;![CDATA[Kyle Swanson]]&gt;</name>
  </customer>
</customers>

This doesn't seem right to me.  Is there a way to see the actual characters '<' and '>' instead of the html equivalents shown in the XML output above?

Thanks in advance for any help!

Answer : CDATA tags appearing incorrectly in XML output using FOR XML PATH

Alright, think I figured out what it was.  I thought it was using UNION earlier, but didn't add the ORDER BY and so wasn't getting proper results.  Just tried with order by and got it working.


;with c
as
(
select 1 as Customer_id, 'Fred' as FirstName, 'Flintstone' as LastName
union select 2, 'Betty', 'Ruble'
)
select 1 as Tag
, 0 as Parent
, Customer_id as "customer!1!customer_id!hide"
, null as "name!2!!CDATA"
from c
union
select 2 as Tag
, 1 as Parent
, Customer_Id
, FirstName + ' ' + LastName as "name!2!!CDATA"
from c
order by "customer!1!customer_id!hide", Tag
for xml explicit, root('customers')
;

The highlighted portion is key to keeping the data organized together properly.  The order by Tag column will ensure that the elements are sequenced correctly.

You can simply add other elements in the same way .  If you want address to be under contacts, then its parent column value needs to be the same as the tag value of the contacts element.

Random Solutions  
 
programming4us programming4us