2
如果我有一個母親爲&父親的家庭的公用表表達式,我該如何增加'Generation'計數器?一個家庭應該讓孩子一代爲零,父母爲一代,父母代爲二代。但循環執行兩次,每組祖父母一次。帶有2個聯合的公用表表達式計數器
;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
完美,謝謝。 – simon831 2010-05-12 11:49:35