SQL Server : FOR XML sorting control by attribute

安稳与你 提交于 2019-11-30 20:06:15

If you want to reorder existing xml, you can use XQuery:

declare @data xml = '
<test>
    <tree abc="123"/>
    <tree abc="789"/>
    <tree-order abc="456"/>
</test>
'

select @data.query('<test>{for $i in test/* order by $i/@abc return $i}</test>')

Result:

<test>
  <tree abc="123" />
  <tree-order abc="456" />
  <tree abc="789" />
</test>

sql fiddle demo

update:

To reorder multiple nodes, you can use XQuery like this:

select @data.query('
    element Main {
        for $j in Main/test
            return element test {
                for $i in $j/* order by $i/@abc return $i
            }
    }
')

sql fiddle demo

update 2

To order by integer values of attributes, use cast as <type>:

select @data.query('
    element Main {
        for $j in Main/test
            return element test {
                for $i in $j/* order by $i/@abc cast as xs:integer?
                    return $i
            }
    }
')

sql fiddle demo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!