SQL Server 父子迭代查询语句

时间:2022-10-06 00:36:53

-- 根据父ID得到所有子ID

-- Get childs by parent id
WITH Tree
AS
(
SELECT Id,ParentId FROM dbo.Node P WHERE P.Id = 21 -- parent id,即父记录
UNION ALL
SELECT C.Id,C.ParentId FROM dbo.Node C
INNER JOIN Tree T ON C.ParentId = T.Id                           -- 所有子记录
)


SELECT * FROM Tree  -- Tree包含父子记录

 

 

-- 根据子ID得到所有父ID

-- Get parents by child id
WITH Tree
AS
(
SELECT Id,ParentId FROM dbo.Node C WHERE C.Id = 57 -- child id,即子记录
UNION ALL
SELECT P.Id,P.ParentId FROM dbo.Node P
INNER JOIN Tree T ON P.Id = T.ParentId                             -- 所有父记录
)
SELECT * FROM Tree  -- Tree包含父子记录