views:

31

answers:

1

If I have a common table expression for a family with mother & father, how can I increment the 'Generation' counter? A family should have the child as generation zero, parents as generation 1, and the four grandparents as generation 2. But the loop is performed twice, one for each set of grandparents.

;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 
+2  A: 

Change the join look at relatives in one generation gap in one go, rather then have 2 recursive clauses in the CTE. The 2 clauses form a a partial cross join which is why you have extra rows

;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 
gbn
perfect, thanks.
simon831