我有两张表如下
Table Person
Id Name
1 A
2 B
3 C
4 D
5 E
Table RelationHierarchy
ParentId CHildId
2 1
3 2
4 3
这将形成类似树的结构
D
|
C
|
B
|
A
我正在使用以下CTE来查找顶级父级
DECLARE @childID INT
SET @childID = 1 --chield to search
;WITH RCTE AS
(
SELECT *, 1 AS Lvl FROM RelationHierarchy
WHERE ChildID = @childID
UNION ALL
SELECT rh.*, Lvl+1 AS Lvl FROM dbo.RelationHierarchy rh
INNER JOIN RCTE rc ON rh.CHildId = rc.ParentId
)
SELECT TOP 1 id, Name
FROM RCTE r
inner JOIN dbo.Person p ON p.id = r.ParentId
ORDER BY lvl DESC
现在的问题是,如果人自己是一个顶级的,那么他的身份证应该被退回而不是没有记录。我是否需要临时表或表变量来检查CTE的计数然后返回 @childID如果Count为零?
答案 0 :(得分:1)
我认为这可以解决您的问题。这个想法是强迫孩子开始而不是最初进行查找:
WITH RCTE AS
(
SELECT @childID as parentId, NULL as childid, 1 AS Lvl
UNION ALL
SELECT rh.*, Lvl+1 AS Lvl FROM dbo.RelationHierarchy rh
INNER JOIN RCTE rc ON rh.CHildId = rc.ParentId
)
SELECT TOP 1 id, Name
FROM RCTE r
inner JOIN dbo.Person p ON p.id = r.ParentId
ORDER BY lvl DESC;