sqlserver递归获取对应子父级
Posted dengjb
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sqlserver递归获取对应子父级相关的知识,希望对你有一定的参考价值。
DECLARE @table TABLE(
id INT NOT NULL
,cityName NVARCHAR(100)
,parentId int NOT null
)
INSERT INTO @table
( id,
cityName,
parentId
)
SELECT 1,‘湖南省‘,0 UNION ALL
SELECT 2,‘长沙市‘,1 UNION ALL
SELECT 3,‘岳阳市‘,1 UNION ALL
SELECT 4,‘芙蓉区‘,2 UNION ALL
SELECT 5,‘开福区‘,2 UNION ALL
SELECT 6,‘岳阳市‘,3 UNION ALL
SELECT 7,‘岳阳楼区‘,3
--SELECT * FROM @table
;WITH CityTree AS --获取对应子级
(
SELECT * FROM @table WHERE id =2--条件
UNION ALL
SELECT b.* FROM CityTree a
INNER JOIN @table b ON a.id = b.parentId
)
SELECT * FROM CityTree
;WITH CityParent AS --获取对应父级
(
SELECT * FROM @table WHERE id =7--条件
UNION ALL
SELECT b.* FROM CityParent a
INNER JOIN @table b ON b.id = a.parentId
)
SELECT * FROM CityParent
以上是关于sqlserver递归获取对应子父级的主要内容,如果未能解决你的问题,请参考以下文章