我有一张(简化的)表格:
OrgName | Hierarchy
---------|------------
Org1 | A
Org2 | AA
Org3 | AB
Org4 | ABA
如果出现以下情况,组织是其他组织的子女:
LEN(Parent.Hierarchy)
完全匹配所以在我的表中:
我的问题是如何编写递归层次结构来查找特定组织的所有后代?我读过的所有CTE示例都有连接的数字条件(如Employee.ManagerID = CTE.EmpID
)。这是我到目前为止所做的:
DELCARE @search VARCHARE = 'A'
WITH Org_cte (OrgName, HLevel, RecursionLevel)
AS
(SELECT o.OrgName, o.Hierarchy, 0 as RecursionLevel
FROM OrgTable o
WHERE o.Hierarchy = @search
UNION ALL
SELECT o.OrgName, o.Hierarchy, RecursionLevel + 1
FROM OrgTable o
INNER JOIN Org_cte
ON ???)
SELECT OrgName, HLevel, Recursion FROM Org_cte
我对CTE很新,谢谢你的帮助!
答案 0 :(得分:0)
编辑:
这应该这样做。我忽略了你从递归级别0开始,并且需要排除相同的级别:
WITH org_cte (OrgName, HLevel, RecursionLevel)
AS
(
SELECT o.OrgName, o.Hierarchy, 1 as RecursionLevel
FROM OrgTable o
WHERE o.Hierarchy = 'A'
UNION ALL
SELECT o.OrgName, o.Hierarchy, RecursionLevel + 1
FROM OrgTable o
JOIN Org_cte
ON substring(o.hierarchy, 1, org_cte.recursionLevel) = org_cte.hlevel
AND o.hierarchy <> org_cte.hlevel
)
SELECT OrgName, HLevel, RecursionLevel
FROM Org_cte