您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

将所有表项的所有父项作为分隔字符串SQL列出在层次结构表中

将所有表项的所有父项作为分隔字符串SQL列出在层次结构表中

这似乎可以解决问题。关键是要意识到我们可以以倒退的方式构建路径,并在我们不再需要父级定位时停止:

DECLARE @t table (ID int not null, Name varchar(19) not null, ParentID int null)
insert into @t(ID,Name,ParentID) values
(1 ,'Alex',null),
(2 ,'John',null),
(3 ,'Don',1),
(4 ,'Philip',2),
(5 ,'Shiva',2),
(6 ,'San',3),
(7 ,'Antony',6),
(8 ,'Mathew',2),
(9 ,'Cyril',8),
(10,'Johan',9)

declare @search table (ID int not null)
insert into @search (ID) values (7),(10)

;With Paths as (
    select s.ID as RootID,t.ID,t.ParentID,t.Name, CONVERT(varchar(max),t.Name) as Path
    from
        @search s
            inner join
        @t t
            on
                s.ID = t.ID
    union all
    select p.RootID,t.ID,t.ParentID,p.Name, t.Name + '->' + p.Path
    from Paths p
            inner join
        @t t
            on
                p.ParentID = t.ID
)
select * from Paths where ParentID is null

结果:

RootID      ID          ParentID    Name                Path
----------- ----------- ----------- ------------------- ----------------------------
10          2           NULL        Johan               John->Mathew->Cyril->Johan
7           1           NULL        Antony              Alex->Don->San->Antony

(我在其他列中保留了有助于显示最终状态的信息。在不进行过滤的情况下查询CTE也可能是有启发性的)

我还要警告,如果可能的话,我通常不会使用带分隔符的字符串-当sql Server具有 设计 用于多个值的类型时,这不是一个很好的表示。

SQLServer 2022/1/1 18:53:23 有517人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶