在层次表中获取孩子的根父级

我有一个包含分层数据的表,结构如下:

I have a table with hierarchical data in it, the structure goes like this:

ID      ParentId
----   ----------
1       NULL
2       1
3       2
4       2
5       3
6       5

如果我传递节点 ID,我想通过在 SQL 中遍历其所有父节点来获取最高节点 ID/详细信息.

If I pass the node Id I would like to get the top most node Id/details by traversing through all its parents in SQL.

我尝试了 CTE,但我无法正确组合.然而,我把它作为一个函数工作,但它太慢了,我不得不发布这个问题.

I tried CTE, i somehow cannot get the combination correct. However, i got this working as a function but it is so slow that i had to post this question.

在上面的示例中,如果我通过 6,我希望获得最高的值,即 1.通过遍历 6 => 5 => 3 => 2 => [1](结果)

In the above example if I pass 6, i would want to have the top most i.e. 1. By traversing through 6 => 5 => 3 => 2 => [1] (result)

提前感谢您的帮助.

推荐答案

请尝试:

declare @id int=6
;WITH parent AS
(
    SELECT id, parentId  from tbl WHERE id = @id
    UNION ALL 
    SELECT t.id, t.parentId FROM parent
    INNER JOIN tbl t ON t.id =  parent.parentid
)

SELECT TOP 1 id FROM  parent
order by id asc

相关文章