單父節點環境
對於單父節點層次結構方案
注 本節中的示例使用一個名為 Employees 的表
以下代碼生成 Employees 表並且用示例數據填充它
USE tempdb
CREATE TABLE Employees
(
empid int NOT NULL
mgrid int NULL
empname varchar(
salary money NOT NULL
CONSTRAINT PK_Employees PRIMARY KEY(empid)
CONSTRAINT FK_Employees_mgrid_empid
FOREIGN KEY(mgrid)
REFERENCES Employees(empid)
)
CREATE INDEX idx_nci_mgrid ON Employees(mgrid)
SET NOCOUNT ON
INSERT INTO Employees VALUES(
INSERT INTO Employees VALUES(
INSERT INTO Employees VALUES(
INSERT INTO Employees VALUES(
INSERT INTO Employees VALUES(
INSERT INTO Employees VALUES(
INSERT INTO Employees VALUES(
INSERT INTO Employees VALUES(
INSERT INTO Employees VALUES(
INSERT INTO Employees VALUES(
INSERT INTO Employees VALUES(
INSERT INTO Employees VALUES(
INSERT INTO Employees VALUES(
INSERT INTO Employees VALUES(
每個雇員都向其 ID 存儲在 mgrid 列中的經理匯報
圖
下面是一些可能在 Employees 表上運行的常見請求
顯示有關 Robert (empid=
顯示有關比 Janet (empid=
顯示通向 James (empid=
顯示有多少個雇員直接或間接向每個經理匯報
以適當的方式顯示所有雇員
遞歸 CTE 提供了處理上述請求(它們在本質上是遞歸的)的手段
第一個請求可能是最常見的一個請求
WITH EmpCTE(empid
AS
(
SELECT empid
FROM Employees
WHERE empid =
UNION ALL
SELECT E
FROM Employees AS E
JOIN EmpCTE AS M
ON E
)
SELECT * FROM EmpCTE
以下為結果集
empid empname mgrid lvl
按照先前描述的遞歸 CTE 邏輯
錨定成員被激活
首先
然後
最後
請注意
使用該級別計數器
WITH EmpCTEJanet(empid
AS
(
SELECT empid
FROM Employees
WHERE empid =
UNION ALL
SELECT E
FROM Employees as E
JOIN EmpCTEJanet as M
ON E
WHERE lvl <
)
SELECT empid
FROM EmpCTEJanet
WHERE lvl =
以下為結果集
empid empname
該代碼示例中比上一個代碼示例增加的代碼以粗體顯示
正如前面提到的那樣
DECLARE @empid AS INT
SET @empid =
SET @lvl =
WITH EmpCTE(empid
AS
(
SELECT empid
FROM Employees
WHERE empid = @empid
UNION ALL
SELECT E
FROM Employees as E
JOIN EmpCTE as M
ON E
WHERE lvl < @lvl
)
SELECT empid
FROM EmpCTE
WHERE lvl = @lvl
您可以使用提示在已經調用一定數量的遞歸迭代之後強行終止查詢
WITH EmpCTE(empid
AS
(
SELECT empid
FROM Employees
WHERE empid =
UNION ALL
SELECT E
FROM Employees as E
JOIN EmpCTE as M
ON E
)
SELECT * FROM EmpCTE
OPTION (MAXRECURSION
以下為結果集
empid empname mgrid lvl
Statement terminated
可能返回(但是不能保證返回)迄今生成的結果
WITH EmpCTE(empid
AS
(
SELECT empid
FROM Employees
WHERE empid =
UNION
From:http://tw.wingwit.com/Article/program/SQLServer/201311/21971.html