SQL 語句遞迴查詢 With AS 查詢所有子節點
create table #EnterPrise
(
Department nvarchar(50),--部門名稱
ParentDept nvarchar(50),--上級部門
DepartManage nvarchar(30)--部門經理
)
insert into #EnterPrise select '技術部','總經辦','Tom'
insert into #EnterPrise select '商務部','總經辦','Jeffry'
insert into #EnterPrise select '商務一部','商務部','ViVi'
insert into #EnterPrise select '商務二部','商務部','Peter'
insert into #EnterPrise select '程式組','技術部','GiGi'
insert into #EnterPrise select '設計組','技術部','yoyo'
insert into #EnterPrise select '專項組','程式組','Yue'
insert into #EnterPrise select '總經辦','','Boss'
--查詢部門經理是Tom的下面的部門名稱
;with hgo as
(
select *,0 as rank from #EnterPrise where DepartManage='Tom'
union all
select h.*,h1.rank+1 from #EnterPrise h join hgo h1 on h.ParentDept=h1.Department
)
select * from hgo
/*
Department ParentDept DepartManage rank
--------------- -------------------- ----------------------- -----------
技術部 總經辦 Tom 0
程式組 技術部 GiGi 1
設計組 技術部 yoyo 1
專項組 程式組 Yue 2
*/
--查詢部門經理是GiGi的上級部門名稱
;with hgo as
(
select *,0 as rank from #EnterPrise where DepartManage='GiGi'
union all
select h.*,h1.rank+1 from #EnterPrise h join hgo h1 on h.Department=h1.ParentDept
)
select * from hgo
/*
Department ParentDept DepartManage rank
-------------------- ---------------------- ----------- -----------
程式組 技術部 GiGi 0
技術部 總經辦 Tom 1
總經辦 Boss 2
*/
如果遞迴次數大於100,只需在與cte連線的sql 語句的最後加上option (maxrecursion 0) 即可.預設遞迴
次數為100,設為0表示沒有次數限制.