码迷,mamicode.com
首页 > 数据库 > 详细

sqlserver递归获取对应子、父级

时间:2020-05-13 13:53:53      阅读:105      评论:0      收藏:0      [点我收藏+]

标签: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

sqlserver递归获取对应子、父级

标签:parentId   nio   sqlserver   长沙   with   tree   name   server   not   

原文地址:https://www.cnblogs.com/dengjb/p/12881804.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!