具有2个联合的公用表表达式计数器

时间:2010-05-12 11:03:10

标签: sql sql-server tsql recursion common-table-expression

如果我有一个与母亲和家庭共同的表格表达式父亲,我怎样才能增加“代”计数器呢?一个家庭应该让孩子为零代,父母为第一代,四个祖父母为第二代。但是循环执行两次,每组祖父母一次。

;WITH FamilyTree
AS
(
    SELECT *, 0 AS Generation
    FROM myTable
    WHERE [id] = 99

    UNION ALL
    SELECT name, Generation + 1
    FROM myTable AS Fam
    INNER JOIN FamilyTree
    ON Fam.[id] = FamilyTree.[motherid]

    UNION ALL
    SELECT name, Generation + 1
    FROM myTable AS Fam
    INNER JOIN FamilyTree
    ON Fam.[id] = FamilyTree.[fatherid]
)
SELECT generation, name FROM FamilyTree 

1 个答案:

答案 0 :(得分:4)

一次更改一代间隙中亲属的连接外观,而不是在CTE中有两个递归子句。这两个子句构成了一个部分交叉连接,这就是为什么你有额外的行

;WITH FamilyTree
AS
(
    SELECT *, 0 AS Generation
    FROM myTable
    WHERE [id] = 99

    UNION ALL
    SELECT name, Generation + 1
    FROM myTable AS Fam
    INNER JOIN FamilyTree
    ON Fam.[id] IN (FamilyTree.[motherid], FamilyTree.[fatherid])
)
SELECT generation, name FROM FamilyTree