• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
Kevin Cheng's Yard
电脑是我的老婆,编程是我的灵魂,代码是我的语言,按键是我在歌唱。
https://github.com/surfsky/
博客园    首页    新随笔    联系   管理    订阅  订阅

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
;

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


 


 

转载请注明出处:http://surfsky.cnblogs.com 

posted @ 2012-11-20 11:27  surfsky  阅读(779)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3