36

I have the following query inside a larger Select statement in SQL Server:

 CONVERT(NVARCHAR(2000),stuff((SELECT '; ' + IsNull(D2.SelectedComments,'')
 FROM #StudentDetails D2
 WHERE D2.STUD_PK = A.STUD_PK AND D2.CourseNo = A.CourseNo
AND D2.Section = A.Section
FOR XML PATH('')),1,2,'')) AS SelectedComments,

This column is generating some strange symbols after certain entries such as This approach is satisfactory .&#x0D. I don't understand where the .&#x0D is coming from. I tried doing SELECT SelectedComments FROM #StudentDetails right before this and I don't see the .&#x0D. Can anyone tell where it could be coming from?

2
  • 0D is the HEX for a carriage return: columbia.edu/kermit/ascii.html
    – valverij
    Commented May 14, 2013 at 15:31
  • I think that's a line feed and carriage return. When you add FOR XML PATH() to your Select statement, certain characters that are not XML friendly are encoded, line feed and carriage returns included. As far as I'm aware, SQL will output valid XML with the correct encoding
    – Rodders
    Commented May 14, 2013 at 15:33

2 Answers 2

61

If you modify your use of For Xml Path, it will do the unescaping for you and you won't need to resort to using the Replace function:

,   Stuff(
        (
        Select '; ' + IsNull( D2.SelectedComments, '' )
        From #StudentDetails As D2
        Where D2.Stud_PK = A.Stud_PK
            And D2.CourseNo = A.CourseNo
            And D2.Section = A.Section
        For Xml Path(''), type
        ).value('.', 'nvarchar(max)')
        , 1, 2, '') As SelectedComments
1
  • so.. by default the "For XML" is returning an XML datatype, with escaped whitespace characters. Makes sense, and even more to be explicit about the datatype you want.
    – Davos
    Commented Sep 22, 2014 at 8:13
7

The &#x0D is a carriage return. You can either clean up the data before inserting it, remove it, or, if you want to keep the formatting, add TYPE to the end of your SELECT:

SELECT * FROM MyData FOR XML PATH(''), TYPE

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.