-- 构建递归结构的表(数据是虚构的)
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
;

sqlserver 递归查询

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


 


 

相关文章:

  • 2022-03-05
  • 2022-12-23
  • 2022-12-23
  • 2021-07-22
  • 2022-12-23
  • 2021-08-05
  • 2022-01-09
猜你喜欢
  • 2021-12-21
  • 2021-09-06
  • 2022-12-23
  • 2022-12-23
  • 2021-06-27
相关资源
相似解决方案