SQL 语句递归查询 With AS 查找所有子节点
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表示沒有次數限制.?
?
總結
以上是生活随笔為你收集整理的SQL 语句递归查询 With AS 查找所有子节点的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java条形码生成(128c)
- 下一篇: linux cmake编译源码,linu