递归查询 CTE 父亲 - 儿子 - 孙子错误

Recursive Query CTE Father - Son - Grandson error

我有一个table,里面有一些项目的ID和IDFATHER,这些项目可以接收N个儿子,所以,结构是这样的

ID IDFATHER REV
1 1 0
2 1 1
5 2 2

我需要从 ID 5 开始转到 ID 1,所以我做了一个 CTE 查询:

WITH lb (ID, IDFATHER) AS (
    SELECT ID, IDFATHER
    FROM PROJECTS
    WHERE ID = 5

    UNION ALL

    SELECT I.ID, I.IDFATHER
    FROM PROJECTS I
    JOIN lb LBI ON I.ID = LBI.IDFATHER
    --WHERE I.ID = LBI.IDFATHER -- Recursive Subquery 
)
SELECT *
FROM lb
WHERE LB.ID = LB.IDFATHER 

当这段代码运行时,它给我:

The statement terminated. The maximum recursion 100 has been exhausted before statement completion.

所以基本上我只是通过添加来处理它:

SELECT TOP 1 * FROM LB WHERE  LB.ID = LB.IDFATHER

但我真的很想知道是我的错误。谁能帮我解决这些问题?

第一个 行指向自身,因此递归永远不会停止。您需要在递归 cte 中添加此条件:

WHERE LBI.ID <> LBI.IDFATHER

我宁愿将第一行的 IDFather 设置为 NULL。

递归没有停止,因为你的第一行无休止地引用它自己。

如果顶行的父行为空,递归就会停止。

另一种方法是使用这种情况 id = parentid 作为终止逻辑。

The fiddle

WITH  LB (ID, IDFATHER, idstart) AS (
    SELECT ID,  IDFATHER, id
      FROM PROJECTS WHERE ID = 5
     UNION ALL 
    SELECT  I.ID,  I.IDFATHER, lbi.idstart
      FROM PROJECTS I 
      JOIN LB LBI
        ON  I.ID = lbi.IDFATHER 
       AND lbi.id <> lbi.idfather
      )

SELECT id AS idtop, idstart
  FROM LB
 WHERE LB.ID = LB.IDFATHER
;

结果: