Finding node order in XML document in SQL Server

前端 未结 6 1396
死守一世寂寞
死守一世寂寞 2020-12-01 04:41

How can I find the order of nodes in an XML document?

What I have is a document like this:


    
            


        
6条回答
  •  Happy的楠姐
    2020-12-01 05:24

    SQL Server's row_number() actually accepts an xml-nodes column to order by. Combined with a recursive CTE you can do this:

    declare @Xml xml = 
    '
        
            
        
        
            
                
                
            
        
    '
    
    ;with recur as (
        select
            ordr        = row_number() over(order by x.ml),
            parent_code = cast('' as varchar(255)),
            code        = x.ml.value('@code', 'varchar(255)'),
            children    = x.ml.query('./value')
        from @Xml.nodes('value') x(ml)
        union all
        select
            ordr        = row_number() over(order by x.ml),
            parent_code = recur.code,
            code        = x.ml.value('@code', 'varchar(255)'),
            children    = x.ml.query('./value')
        from recur
        cross apply recur.children.nodes('value') x(ml)
    )
    select *
    from recur
    where parent_code = '121'
    order by ordr
    

    As an aside, you can do this and it'll do what do you expect:

    select x.ml.query('.')
    from @Xml.nodes('value/value')x(ml)
    order by row_number() over (order by x.ml)
    

    Why, if this works, you can't just order by x.ml directly without row_number() over is beyond me.

提交回复
热议问题