t-sql recursive query

前端 未结 5 1024
星月不相逢
星月不相逢 2021-02-06 08:03

Based on an existing table I used CTE recursive query to come up with following data. But failing to apply it a level further.

Data is as below

id    nam         


        
5条回答
  •  逝去的感伤
    2021-02-06 08:13

    Here's an example CTE to do that:

    declare @t table (id int, name varchar(max), parentid int)
    
    insert into @t select 1,     'project'  , 0
    union all select 2,     'structure' , 1
    union all select 3,     'path_1'    , 2
    union all select 4,     'path_2'    , 2
    union all select 5,     'path_3'    , 2
    union all select 6,     'path_4'    , 3
    union all select 7,     'path_5'    , 4
    union all select 8,     'path_6'    , 5
    
    ; with CteAlias as (
        select id, name, parentid
        from @t t
        where t.parentid = 0
        union all
        select t.id, parent.name + '\' + t.name, t.parentid
        from @t t
        inner join CteAlias parent on t.parentid = parent.id
    )
    select * 
    from CteAlias
    

提交回复
热议问题