1. 程式人生 > >【Sql Server】SQL SERVER 遞歸查詢

【Sql Server】SQL SERVER 遞歸查詢

express pin exp table 分組 bsp 字段 字符串 weight

原文:【Sql Server】SQL SERVER 遞歸查詢

  SQL SERVER 2005之前的版本只能用函數方法實現,SQL SERVER 2005之後新增了CTE功能,可以利用CTE實現遞歸查詢;

  CTE:公用表達式Common Table Expression 是SQL SERVER 2005版本之後引入的一個特性;

#填充測試數據

1、sql

 1 Create table GroupInfo([Id] int,[GroupName] nvarchar(50),[ParentGroupId] int)
 2 
 3 Insert GroupInfo
 4 
 5 select
0,某某大學,null union all 6 7 select 1,外語學院,0 union all 8 select 2,英語專業,1 union all 9 select 3,日語專業,1 union all 10 select 4,英語專業一班,2 union all 11 select 5,英語專業二班,2 union all 12 select 6,日語專業一班,3 union all 13 select 7,日語專業二班,3 union all 14 15 select 8, 法學院,0 union all 16 select
9, 刑法學專業,8 union all 17 select 10,經濟法學專業,8 union all 18 select 11,刑法學專業一班,9 union all 19 select 12,刑法學專業二班,9 union all 20 select 13,經濟法學專業一班,10 union all 21 select 14,經濟法學專業二班,10

2、效果圖

技術分享圖片

#遞歸實現Demo

1、根據指定的節點向上獲取所有父節點,向下獲取所有子節點

 1 --根據指定的節點向下獲取所有子節點
 2 with
 3 CTE
 4 as
 5 (
6 select * from GroupInfo where Id=1 7 union all 8 select G.* from CTE inner join GroupInfo as G 9 on CTE.Id=G.ParentGroupId 10 ) 11 select * from CTE order by Id

 1 --根據指定的節點向上獲取所有父節點
 2 with
 3 CTE
 4 as
 5 (
 6     select * from GroupInfo where Id=14
 7     union all
 8     select G.* from CTE inner join GroupInfo as G
 9     on CTE.ParentGroupId=G.Id
10 )
11 select * from CTE order by Id

2、構造遞歸路徑

 1 --構造遞歸路徑
 2 with
 3 CTE
 4 as
 5 (
 6     select Id,GroupName,ParentGroupId,GroupPath=CAST( GroupName as nvarchar(max)) from GroupInfo where Id=1
 7     union all
 8     select G.*,CAST(CTE.GroupPath+//+G.GroupName as nvarchar(max)) as GroupPath from CTE 
 9     inner join GroupInfo as G
10     on CTE.Id=G.ParentGroupId
11 )
12 select * from CTE

技術分享圖片

3、分組遞歸,將同一條分支上節點放到一起

 1 --通過id字段的字符串的拼接,形成sort字段,再通過sort排序,來實現同一分支上的節點放到一起
 2 WITH    
 3 CTE
 4 AS 
 5 ( 
 6     SELECT * ,CAST(RIGHT(000 + CAST([Id] AS VARCHAR), 3) AS VARCHAR(MAX)) AS sort FROM GroupInfo
 7     WHERE ParentGroupId = 0
 8     UNION ALL
 9     SELECT   GroupInfo.* ,CAST(sort + RIGHT(000 + CAST(GroupInfo.[Id] AS VARCHAR),3) AS VARCHAR(MAX)) AS sort
10     FROM CTE
11     INNER JOIN GroupInfo ON CTE.Id = GroupInfo.ParentGroupId
12 )
13 SELECT * FROM CTE ORDER BY sort 

技術分享圖片

4、遞歸層級查詢(查詢出節點所屬的層級)

1 --查詢節點層級
2 WITH CTE AS (
3     SELECT *,1 AS [Level] FROM GroupInfo WHERE ParentGroupId=0
4     UNION ALL
5     SELECT G.*,CTE.Level+1 FROM GroupInfo as G 
6     JOIN CTE ON CTE.Id =G.ParentGroupId
7 )
8 SELECT * FROM CTE

技術分享圖片

【Sql Server】SQL SERVER 遞歸查詢