列出所有父母层次结构以分隔字符串形式排列最顶端的节点

问题描述:

Im在stackoverflow本身已经回答问题时遇到问题 (Question before)。所以,我只是重复的问题有,因为根元素的一些变化并在它的麻烦列出所有父母层次结构以分隔字符串形式排列最顶端的节点

我有一个SQL表这样

ID  Name  ParentID 
------------------------------ 
0  Users   NULL 
1  Alex   0 
2  John   0 
3  Don   1 
4  Philip  2 
5  Shiva   2 
6  San   3 
7  Antony  6 
8  Mathew  2 
9  Cyril   8 
10  Johan   9 
------------------------- 

正找一个出来把这样

如果我通过ID 7,10,1

该出把表将

ID   Name   Relation 
------------------------------------ 
7   Antony   Alex->Don->San->Antony 
10   Johan   John->Mathew->Cyril->Johan 
1   Alex   - 

从上面的答案我试图强调的是它不应该考虑ID为0且parentid为空的最顶端节点的用户。因此,对于ID 1,它返回的关系,或只是连字符只是一个空字符串( - ) 我怎样才能做到这一点使用CTE

prev answer基于:

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), (1); 

;With Paths as (
    select s.ID as RootID,t.ID,t.ParentID,t.Name 
    , CASE WHEN t.ParentId IS NULL THEN '-' 
      ELSE CONVERT(varchar(max),t.Name) END as Path 
    from @search s 
    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 
    join @t t 
     on p.ParentID = t.ID 
) 
select * 
from Paths 
where ParentID is null; 

Rextester Demo

+0

非常感谢。它效果很好。但不是在ID列显示0显示实际ID的任何可能ID –

+0

@sforsandeep'而不是在ID列显示0显示实际ID的任何可能性对不起,但我不太清楚,如果我理解正确。请准备演示。 – lad2025

+0

对不起...有点改变..我没有注意到它。表中的行不同。没有共同的根'用户'0(我的表中的第一行)。在我的结果是排除用户节点的问题。如果遇到这种情况,您可以修改答案吗?当我添加该行时。 http://rextester.com/discussion/GOPBF14985/Hierarchy-table-to-exclude-root –

根据您的模式和数据,此查询:

with P as 
(
    select *, cast(null as nvarchar) as chain from People where parentID is null 
     union all 
      select C.*, cast(coalesce(P.chain, P.name) + '->' + C.name as nvarchar) 
       from People C inner join P on C.parentID = P.id 

) 

select id, name, coalesce(chain, '-') relation from P where id in (7, 10, 1) 

产量:

id name relation 
----- ------ ------------------------------ 
1  Alex - 
10 Johan John->Mathew->Cyril->Johan 
7  Antony Alex->Don->San->Antony 

Rextester Demo