I was asked this question in one of the SQL Server forums recently. The OP wanted to generate an XML document with CDATA sections and NAMESPACE declarations.
SQL Server 2005 introduced WITH XMLNAMESPACES() which is very handy to generate namespace declarations in the output XML document generated by FOR XML. FOR XML EXPLICIT can be used to generate CDATA sections in the XML output. However, what is interesting is that you cannot use WITH XMLNAMESPACES and FOR XML EXPLICIT together.
Here is a FOR XML EXPLICIT query that generate CDATA sections as well as XML NAMESPACE declarations in the output XML document.
1 AS Tag,
NULL AS Parent,
'Jacob' AS 'Person!1!Name!element',
'Hello world' AS 'Person!1!Greeting!CDATA',
FOR XML EXPLICIT
Here is the output
Tags: XML, FOR-XML-EXPLICIT, FOR XML, XMLNAMESPACES, jacob,