SQL2005 Common Table Expressions(CET)即通用表表達式。html
SQLSERVER CET遞歸使用案例:spa
一、普通案例.net
表結構以下:htm
;WITH cet_depart
AS
(
SELECT depart_id, depart_name FROM dbo.Depart
WHERE depart_id = '004' --入口
UNION ALL --遞歸時必要
SELECT d.depart_id, d.depart_name FROM depart d INNER JOIN cet_depart c
ON CAST (c.depart_id AS INT) = d.upper_depart_id --遞歸條件
)
SELECT * FROM cet_depart
OPTION (MAXRECURSION 20) --最大遞歸次數
結果集:
二、經典實戰
IF OBJECT_ID('Dept') IS NOT NULL
DROP TABLE Dept
go
CREATE TABLE Dept (Id INT , ParentId INT , DeptName NVARCHAR(10))
INSERT Dept
SELECT 1 , 0 , N'食品'
UNION ALL
SELECT 2 , 1 , N'水果'
UNION ALL
SELECT 3 , 1 , N'蔬菜'
UNION ALL
SELECT 4 , 2 , N'香蕉'
UNION ALL
SELECT 5 , 2 , N'蘋果'
UNION ALL
SELECT 6 , 3 , N'青菜'
UNION ALL
SELECT 11 , 0 , N'計算機'
UNION ALL
SELECT 12 , 11 , N'軟件'
UNION ALL
SELECT 13 , 11 , N'硬件'
UNION ALL
SELECT 14 , 12 , N'Office'
UNION ALL
SELECT 15 , 12 , N'Emeditor'
UNION ALL
SELECT 16 , 13 , N'內存'
;WITH cte AS
(
SELECT Id,ParentId,DeptName FROM Dept WHERE id=2
UNION ALL
SELECT a.Id,a.ParentId,a.DeptName FROM Dept a,cte b WHERE a.ParentId=b.Id
)
SELECT * FROM cte
;WITH cte AS
(
SELECT Id,ParentId,DeptName FROM Dept WHERE id=16
UNION ALL
SELECT a.Id,a.ParentId,a.DeptName FROM Dept a,cte b WHERE a.Id=b.ParentId
)
SELECT * FROM cte
;WITH cte AS
(
SELECT Id,ParentId,DeptName,Path=CAST(DeptName AS VARCHAR(MAX)) FROM Dept WHERE parentid=0
UNION ALL
SELECT a.Id,a.ParentId,a.DeptName,CAST(b.Path +'/'+a.DeptName AS VARCHAR(MAX)) FROM Dept a,cte b WHERE a.ParentId=b.Id
)
SELECT * FROM cte