数据库

位置:IT落伍者 >> 数据库 >> 浏览文章

使用SQLSERVER 2005/2008 递归CTE查询树型结构的方法


发布日期:2021年06月13日
 
使用SQLSERVER 2005/2008 递归CTE查询树型结构的方法
下面是一个简单的Family Tree 示例

复制代码 代码如下:

DECLARE @TT TABLE (ID intRelation varchar()Name varchar()ParentID int)

INSERT @TT SELECT Great GrandFather Thomas Bishop null UNION ALL

SELECT Grand Mom Elian Thomas Wilson UNION ALL

SELECT Dad James Wilson UNION ALL

SELECT Uncle Michael Wilson UNION ALL

SELECT Aunt Nancy Manor UNION ALL

SELECT Grand Uncle Michael Bishop UNION ALL

SELECT Brother David James Wilson UNION ALL

SELECT Sister Michelle Clark UNION ALL

SELECT Brother Robert James Wilson UNION ALL

SELECT Me Steve James Wilson

Query

;WITH FamilyTree

AS(

SELECT * CAST(NULL AS VARCHAR()) AS ParentName AS Generation FROM @TT

WHERE ParentID IS NULL

UNION ALL

SELECT Fam*FamilyTreeName AS ParentName Generation + FROM @TT AS Fam

INNER JOIN FamilyTree ON FamParentID = FamilyTreeID

)SELECT * FROM FamilyTree

Output:

希望对您有帮助

Author: Petter Liu

上一篇:SQL Server面试题 面试要点

下一篇:SQLServer 2008中SQL增强之二 Top新用途