码迷,mamicode.com
首页 > 数据库 > 详细

树状sql--采用递归方式获取节点

时间:2016-11-22 12:08:22      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:prim   key   proc   union all   har   sql   节点   http   com   

创建数据库

create table City
(
id varchar(3) primary key ,
pid varchar(3) ,
name varchar(10)
)

插入数据

insert into City values(‘001‘ , null , ‘广东省‘);
insert into City values(‘002‘ , ‘001‘ , ‘广州市‘);
insert into City values(‘003‘ , ‘001‘ , ‘深圳市‘) ;
insert into City values(‘004‘ , ‘002‘ , ‘天河区‘) ;
insert into City values(‘005‘ , ‘003‘ , ‘罗湖区‘);
insert into City values(‘006‘ , ‘003‘ , ‘福田区‘) ;
insert into City values(‘007‘ , ‘003‘ , ‘宝安区‘) ;
insert into City values(‘008‘ , ‘007‘ , ‘西乡镇‘) ;
insert into City values(‘009‘ , ‘007‘ , ‘龙华镇‘);
insert into City values(‘010‘ , ‘007‘ , ‘松岗镇‘);

insert into City values(‘011‘ , null , ‘中国‘);  

 

递归子节点的存储过程:

create proc ProcCity
@id nvarchar(36)
as
begin
with cte as
(
select a.id,a.name,a.pid from City a where id=@id
union all
select k.id,k.name,k.pid from City k inner join cte c on c.id = k.pid
)select * from cte
end

获取深圳以及深圳的所有区:exec ProcCity ‘003‘

技术分享

 

递归父节点的存储过程:

create proc ProcCity
@id nvarchar(36)
as
begin
with cte as 

select a.id,a.name,a.pid from City a where id=@id 
union all 
select k.id,k.name,k.pid from City k inner join cte c on k.id = c.pid 
)select * from cte 
end

获取深圳以及深圳的所有父节点:exec ProcCity ‘003‘

技术分享

 

树状sql--采用递归方式获取节点

标签:prim   key   proc   union all   har   sql   节点   http   com   

原文地址:http://www.cnblogs.com/zxh8080/p/6088264.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!