Home > Database > Mysql Tutorial > 使用SQLSERVER 2005/2008 递归CTE查询树型结构的方法

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

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-07 18:06:32
Original
1046 people have browsed it

我们经常遇到树型结构,把它们显示在一个类似TreeView控件上的情况。这时我们可以使用Recursive Common Table Expressions(CTE)实现

下面是一个简单的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

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Issues
php递归疑惑?
From 1970-01-01 08:00:00
0
0
0
javascript - 关于json数组递归的问题
From 1970-01-01 08:00:00
0
0
0
Vue.js 3中的单文件组件中的递归
From 1970-01-01 08:00:00
0
0
0
javascript - 递归算法问题.
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template