首页 > 代码库 > SqlServer 树结构数据 子节点父节点的查询

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


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
*/

 

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