SQL Server : FOR XML sorting control by attribute

前端 未结 1 1188
南方客
南方客 2021-01-05 09:19

I am generating a XML file from a SQL Server query.

I have some problem about sorting elements issues.

For example, there is simple code as below.

         


        
相关标签:
1条回答
  • 2021-01-05 09:58

    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

    0 讨论(0)
提交回复
热议问题