Printing tree with SQL CTE

后端 未结 1 1902
-上瘾入骨i
-上瘾入骨i 2020-12-20 16:42

The schema is as follows:

CREATE TABLE [Structure](
    [StructureId] [uniqueidentifier] NOT NULL,
    [SequenceNumber] [int] NOT NULL, -- order for siblings         


        
相关标签:
1条回答
  • 2020-12-20 17:35

    Edited after comment. You could add the path to a node, and order on that:

    declare @t table (id int, parent int)
    insert @t (id, parent) values (1, null), (2,1), (3,2), (4,3), (5,null), (6,5)
    
    ; with cte as (
        select  id, parent
        ,       cast(RIGHT(REPLICATE('0',12) + 
                     CONVERT(varchar(12),id),12) as varchar(max)) Path
        from    @t
        where   parent is null
        union all
        select  child.id, child.parent
        ,       parent.Path + RIGHT(REPLICATE('0',12) + 
                                    CONVERT(varchar(12),child.id),12) as Path
        from    @t child
        join    cte parent
        on      parent.id = child.parent
    )
    select  *
    from    cte
    order by
            Path
    

    This prints the root first, followed by leaves in order. If your id can be larger than 12 digits, increase the number in the char(x) casts.

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