您的位置:首页 > 博客中心 > 数据库 >

SqlServer 树结构数据 子节点父节点的查询

时间:2022-03-13 23:24


declare @t table (C_ID int,PcName varchar(6),ParentID int)
insert into @t
select 1,‘安徽‘,0 union all
select 2,‘安庆‘,1 union all
select 3,‘安庆市‘,2 union all
select 4,‘怀宁县‘,2 union all
select 5,‘潜山县‘,2 union all
select 6,‘宿松县‘,2 union all
select 7,‘太湖县‘,2 union all
select 8,‘桐城市‘,2 union all
select 9,‘望江县‘,2 union all
select 10,‘岳西县‘,2 union all
select 11,‘枞阳县‘,2

;with maco as
(
select * from @t where c_id=11
union all
select t.* from @t t,maco m where t.C_ID=m.ParentID
)
select * from maco order by c_id

/*
C_ID PcName ParentID
----------- ------ -----------
1 安徽 0
2 安庆 1
11 枞阳县 2
*/

 

热门排行

今日推荐

热门手游