标签:parentId nio sqlserver 长沙 with tree name server not
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
标签:parentId nio sqlserver 长沙 with tree name server not
原文地址:https://www.cnblogs.com/dengjb/p/12881804.html