首页 > 数据库技术 > 详细

T-SQL查询:WITH AS 递归计算某部门的所有上级机构或下级机构

时间:2018-07-17 00:02:35      阅读:246      评论:0      收藏:0      [点我收藏+]
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 递归计算某部门的所有上级机构或下级机构

原文:https://www.cnblogs.com/jiuge/p/9321128.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!