T-SQL查询:WITH AS 递归计算某部门的所有上级机构或下级机构
Posted 你好柴九
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了T-SQL查询:WITH AS 递归计算某部门的所有上级机构或下级机构相关的知识,希望对你有一定的参考价值。
drop table #Area; CREATE TABLE #Area ( id INT NOT NULL, city_name NVARCHAR(100) NOT NULL, parent_id INT NOT NULL ) INSERT INTo #Area(id,city_name,parent_id) VALUES(1,‘江苏省‘,0) INSERT INTo #Area(id,city_name,parent_id) VALUES(2,‘常州市‘,1) INSERT INTo #Area(id,city_name,parent_id) VALUES(3,‘天宁区‘,2) INSERT INTo #Area(id,city_name,parent_id) VALUES(4,‘新北区‘,2) INSERT INTo #Area(id,city_name,parent_id) VALUES(5,‘天宁区_1‘,3) INSERT INTo #Area(id,city_name,parent_id) VALUES(6,‘新北区_1‘,4) ------------------------------------------------- --根据节点ID获取所有子节点 ------------------------------------------------- SELECT * FROM #Area; WITH AreaTree AS ( SELECT * from #Area where id = 1--需要查找的节点 UNION ALL SELECT #Area.* from AreaTree JOIN #Area on AreaTree.id = #Area.parent_id ) SELECT * FROM AreaTree; ------------------------------------------------- --根据节点ID获取所有父节点 ------------------------------------------------- SELECT * FROM #Area; with AreaTree AS ( SELECT * from #Area where Id=6 --需要查找的节点 UNION ALL SELECT #Area.* from AreaTree JOIN #Area on AreaTree.parent_id= #Area.Id ) SELECT * from AreaTree;
以上是关于T-SQL查询:WITH AS 递归计算某部门的所有上级机构或下级机构的主要内容,如果未能解决你的问题,请参考以下文章
MySQL - WITH RECURSIVE AS 递归查询