Sql 以分隔字符串列出所有父层次结构(不包括最顶端的节点)

Sql 以分隔字符串列出所有父层次结构(不包括最顶端的节点),sql,tsql,sql-server-2012,hierarchical-data,sql-function,Sql,Tsql,Sql Server 2012,Hierarchical Data,Sql Function,我对stackoverflow本身已经回答过的问题感到困扰。所以我只是重复了这个问题,因为有一个根元素,所以有一些改动和麻烦 我有一个这样的SQL表 ID Name ParentID ------------------------------ 0 Users NULL 1 Alex 0 2 John 0 3 Don 1 4 P

我对stackoverflow本身已经回答过的问题感到困扰。所以我只是重复了这个问题,因为有一个根元素,所以有一些改动和麻烦

我有一个这样的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        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和节点为空的节点节点最多的用户。因此,对于ID 1,它只返回一个空字符串作为关系,或者只返回连字符(-) 我如何在以下基础上使用CTE实现这一点:


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

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

.

非常感谢。它工作得很好。但不是在ID列显示0,而是显示实际ID@sforsandeep
但是没有在ID列显示0,而是显示实际ID的任何可能性
对不起,我不太确定我是否理解正确。请准备演示。对不起。。。一点零钱。。我没有注意到。表中的行不同。没有parentid为0(我表中的第一行)的公共根“users”。在我的问题中,排除了users节点。在这种情况下,请修改答案。当我添加那一行时。好啊我遇到麻烦了。。我将其修改为parentid=0,解决了这个问题