Search code examples
sqlxmlxquery-sql

Sort all attributes of XML in SQL query using XQuery


How can get the XML with sorted attributes using XQuery in SQL?

for example for this XML:

<root><book b='' c='' a=''/></root>

must return:

<root><book a='' b='' c=''/></root>

Solution

  • From Limitations of the xml Data Type.

    The order of attributes in an XML instance is not preserved. When you query the XML instance stored in the xml type column, the order of attributes in the resulting XML may be different from the original XML instance.

    So even if you could figure out a way of sorting the attributes, you can not trust that the XML data type in SQL Server will preserve the order you want.