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;

  

posted @ 2018-07-16 23:47  你好柴九  阅读(698)  评论(0编辑  收藏  举报