sqlserver 递归查询

-- 构建递归结构的表(数据是虚构的)
drop table t;
create table t
(
  id int, name varchar(6), pid 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,'太湖县',3 union all
select 8,'桐城市',3 union all
select 9,'望江县',4 union all
select 10,'岳西县',4 union all
select 11,'枞阳县',2
;

 

-- 递归查询某个节点的所有父节点
;with cte as
(
select * from t where id=11
union all
select t.* from t,cte where t.id=cte.pid
)
select * from cte order by id;

 

-- 递归查询整个树
;with cte(id, name, pid, lvl) as
(
 select t.*, 0 lvl from t where pid=0
 union all
 select t.*, cte.lvl+1 lvl from t, cte where t.pid = cte.id
)
select
  case
    when lvl=0 then name
    else REPLICATE(' ', lvl) + '└' + name
  end,
  id,
  pid
from cte
;

但是,这个结果排序是有问题的,如太湖县应该挂在安庆县下面。如果解决这个问题?请不啻指教


 


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值