CTE(Common Table Expressions) 遞迴查詢

--建立測試資料表
DECLARE @tbl_Dept TABLE (
UniqueID int IDENTITY,
DeptID varchar(50),
DeptName varchar(100),
ParentDeptID varchar(50)
)
--建立測試資料
INSERT INTO @tbl_Dept (DeptID,DeptName,ParentDeptID) VALUES ('A1','董事長',NULL)
INSERT INTO @tbl_Dept (DeptID,DeptName,ParentDeptID) VALUES ('B1','資訊部','A1')
INSERT INTO @tbl_Dept (DeptID,DeptName,ParentDeptID) VALUES ('B2','會計部','A1')
INSERT INTO @tbl_Dept (DeptID,DeptName,ParentDeptID) VALUES ('B3','總務部','A1')
INSERT INTO @tbl_Dept (DeptID,DeptName,ParentDeptID) VALUES ('C1','系統應用課','B1')
INSERT INTO @tbl_Dept (DeptID,DeptName,ParentDeptID) VALUES ('C2','系統開發課','B1')
INSERT INTO @tbl_Dept (DeptID,DeptName,ParentDeptID) VALUES ('C3','網路管理課','B1')
INSERT INTO @tbl_Dept (DeptID,DeptName,ParentDeptID) VALUES ('C4','成本課','B2')
INSERT INTO @tbl_Dept (DeptID,DeptName,ParentDeptID) VALUES ('C5','會計課','B2')
INSERT INTO @tbl_Dept (DeptID,DeptName,ParentDeptID) VALUES ('C6','人事課','B3')
--列出部門階層
;WITH DEPT_CTE(DeptID,DeptName,Path,Degree) AS
(
SELECT DeptID,DeptName,CAST(DeptName AS nvarchar(max)), 0 AS Degree
FROM @tbl_Dept
WHERE ParentDeptID IS NULL
UNION ALL
SELECT D.DeptID,D.DeptName,CAST(DC.Path + ' > ' + D.DeptName AS nvarchar(max)),Degree + 1
FROM @tbl_Dept D
INNER JOIN DEPT_CTE DC
ON D.ParentDeptID = DC.DeptID
)
SELECT * FROM Dept_CTE ORDER BY Degree
view raw CTE.sql hosted with ❤ by GitHub
DeptID DeptName Path Degree
A1 董事長 董事長 0
B1 資訊部 董事長 > 資訊部 1
B2 會計部 董事長 > 會計部 1
B3 總務部 董事長 > 總務部 1
C1 系統應用課 董事長 > 資訊部 > 系統應用課 2
C2 系統開發課 董事長 > 資訊部 > 系統開發課 2
C3 網路管理課 董事長 > 資訊部 > 網路管理課 2
C4 成本課 董事長 > 會計部 > 成本課 2
C5 會計課 董事長 > 會計部 > 會計課 2
C6 人事課 董事長 > 總務部 > 人事課 2
view raw Result.md hosted with ❤ by GitHub

多個SQL變數使用於in查詢

declare @values table
(
Value varchar(1000)
)
insert into @values values ('A')
insert into @values values ('B')
insert into @values values ('C')
select blah
from foo
where myField in (select value from @values)
view raw query.sql hosted with ❤ by GitHub