标签: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‘
标签:prim key proc union all har sql 节点 http com
原文地址:http://www.cnblogs.com/zxh8080/p/6088264.html