sql递归 with查询所有上级或所有下级

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;

你可能感兴趣的:(SqlServer)