I need to store the text of all of the stored procedures in a database into an XML data type. When I use, FOR XML PATH
, the text within in the stored procedure
When I use, FOR XML PATH, the text within in the stored procedure contains serialized data characters like and for CRLF and ", etc.
Yes, because that's how XML works. To take a clearer example, suppose your sproc contained this text:
IF @someString = '<' THEN
then to store it in XML, there must be some kind of encoding applied, since you can't have a bare <
in the middle of your XML (I hope you can see why).
The real question is then not 'how do I stop my text being encoded when I store it as XML', but rather (as you guess might be the case):
Or when I parse the xml data type to recreate the stored procedure can I deserialize it so that it does not have those characters?
Yes, this is the approach you should be looking at.
You don't how us how you're getting your text out of the XML at the moment. The key thing to remember is that you can't (or rather shouldn't) treat XML as 'text with extra bits' - you should use methods that understand XML.
If you're extracting the text in T-SQL itself, use the various XQuery options. If in C#, use any of the various XML libraries. Just don't do a substring operation and expect that to work...
An example, if you are extracting in T-SQL:
DECLARE @someRandomText nvarchar(max) = 'I am some arbitrary text, eg a sproc definition.
I contain newlines
And arbitrary characters such as < > &
The end.';
-- Pack into XML
DECLARE @asXml xml = ( SELECT @someRandomText FOR XML PATH ('Example'), TYPE );
SELECT @asXml;
-- Extract
DECLARE @textOut nvarchar(max) = ( SELECT @asXml.value('.', 'nvarchar(max)') ) ;
SELECT @textOut;
But you can find many many tutorials on how to get values out of xml-typed data; this is just an example.