我有一个具有这种结构的表:
ParentProjectID ChildProjectID
------------------------------
101 102
102 103
103 104
201 202
202 203
让我解释一下这个场景,当我们更新一个项目时,我们将其视为一个新项目并将其输入到其父项目下。
比如 102 是其父 102 的子项目,子 103 的父项目是 102,依此类推。
现在,我的问题是找出祖 parent 、 parent 和 child 。
在上面的例子中,101 是 102,103 和 104 的祖 parent 。而 102 是 103 和 104 的 parent 。
所以,我希望我的结果是:
(如果我将 101 作为 ParentProjectID
的参数传递)
ParentProjectID ChildProjectID
101 102
101 103
101 104
我们将不胜感激。
最佳答案
您可以使用递归公用表表达式:
create procedure usp_Descendants
(
@ParentProjectID int
)
as
begin
;with cte as (
select
T.ChildProjectID
from Table1 as T
where T.ParentProjectID = @ParentProjectID
union all
select
T.ChildProjectID
from cte as c
inner join Table1 as T on T.ParentProjectID = c.ChildProjectID
)
select
@ParentProjectID, c.ChildProjectID
from cte as c
end
exec usp_Descendants @ParentProjectID = 101;
-----------
101 102
101 103
101 104
exec usp_Descendants @ParentProjectID = 101;
-----------
102 103
102 104
关于sql - SQL Server 中的父子关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18934496/