下面是一个简单的Family Tree 示例:
复制代码 代码如下:
DECLARE @TT TABLE (ID int,Relation varchar(25),Name varchar(25),ParentID int)
INSERT @TT SELECT 1,' Great GrandFather' , 'Thomas Bishop', null UNION ALL
SELECT 2,'Grand Mom', 'Elian Thomas Wilson' , 1 UNION ALL
SELECT 3, 'Dad', 'James Wilson',2 UNION ALL
SELECT 4, 'Uncle', 'Michael Wilson', 2 UNION ALL
SELECT 5, 'Aunt', 'Nancy Manor', 2 UNION ALL
SELECT 6, 'Grand Uncle', 'Michael Bishop', 1 UNION ALL
SELECT 7, 'Brother', 'David James Wilson',3 UNION ALL
SELECT 8, 'Sister', 'Michelle Clark', 3 UNION ALL
SELECT 9, 'Brother', 'Robert James Wilson', 3 UNION ALL
SELECT 10, 'Me', 'Steve James Wilson', 3
----------Query---------------------------------------
;WITH FamilyTree
AS(
SELECT *, CAST(NULL AS VARCHAR(25)) AS ParentName, 0 AS Generation FROM @TT
WHERE ParentID IS NULL
UNION ALL
SELECT Fam.*,FamilyTree.Name AS ParentName, Generation + 1 FROM @TT AS Fam
INNER JOIN FamilyTree ON Fam.ParentID = FamilyTree.ID
)SELECT * FROM FamilyTree
Output:
希望对您有帮助
Author: Petter Liu
您可能感兴趣的文章:- 使用SqlServer CTE递归查询处理树、图和层次结构
- 在sqlserver中如何使用CTE解决复杂查询问题
- SQLSERVER2008中CTE的Split与CLR的性能比较
- SQLSERVER2005 中树形数据的递归查询
- sqlserver另类非递归的无限级分类(存储过程版)
- SqlServer使用公用表表达式(CTE)实现无限级树形构建