Storing the text of a stored procedure in an XML data type in SQL Server

后端 未结 3 1133
故里飘歌
故里飘歌 2020-12-21 14:54

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

3条回答
  •  暖寄归人
    2020-12-21 15:45

    If you want to store data with special characters within XML, there are two options (plus a joke option)

    • escaping
    • CDATA
    • just to mention: Convert everything to base64 or similar would work too :-)

    The point is: You do not need this!

    The only reason for CDATA (at least for me) is manually created content (copy'n'paste or typing). Whenever you build your XML automatically, you should rely on the implicitly applied escaping.

    Why does it bother you, how the data is looking within the XML?

    If you read this properly (not with SUBSTRING or other string based methods), you will get it back in the original look.

    Try this:

    DECLARE @TextWithSpecialCharacters NVARCHAR(100)=N'€ This is' + CHAR(13) + 'strange  And Ampersand &&&';
    
    SELECT @TextWithSpecialCharacters FOR XML PATH('test');
    

    returns

    € This is
    strange <ups, angular brackets! > And Ampersand &&&
    

    But this...

    SELECT (SELECT @TextWithSpecialCharacters FOR XML PATH('test'),TYPE).value('/test[1]','nvarchar(100)');
    

    ...returns

    € This is
    strange  And Ampersand &&&
    

    Microsoft decided not even to support this with FOR XML (except EXPLICIT, which is a pain in the neck...)

    Read two related answers (by me :-) about CDATA)

    • https://stackoverflow.com/a/38547537/5089204
    • https://stackoverflow.com/a/39034049/5089204 (with further links...)

提交回复
热议问题