当前位置: 移动技术网 > IT编程>数据库>MSSQL > SQL Server 树形表非循环递归查询的实例详解

SQL Server 树形表非循环递归查询的实例详解

2017年12月08日  | 移动技术网IT编程  | 我要评论

性爱,婚车布置,男人之虎

很多人可能想要查询整个树形表关联的内容都会通过循环递归来查...事实上在微软在sql2005或以上版本就能用别的语法进行查询,下面是示例。

--通过子节点查询父节点
with 
tree as( 
select * from areas 
where id = 6 -- 要查询的子 id 
union all 
select areas.* from areas, tree 
where tree.pid = areas.id
) 
select area from tree
--通过父节点查询子节点
with 
tree as( 
select * from areas 
where id = 7 -- 要查询的子 id 
union all 
select areas.* from areas, tree 
where tree.id = areas.pid
) 
select area from tree

通过子节点查询父节点查询结果为:

修改代码为

--通过子节点查询父节点
declare @area varchar(8000);
with 
tree as( 
select * from areas 
where id = 6 -- 要查询的子 id 
union all 
select areas.* from areas, tree 
where tree.pid = areas.id
)
select @area=isnull(@area,'')+area from tree order by id 
select area= @area

则结果为:中国北京市丰台区

根据以上可以将这段代码封装为一个存储过程

-----存储过程,递归获取树形地区表字符串
if exists (select * from sysobjects where name='sp_getareastr')
drop proc sp_getareastr
go
create procedure sp_getareastr 
@id int
as
declare @area varchar(8000)
begin
with 
tree as( 
select * from areas 
where id = @id -- 要查询的子 id 
union all 
select areas.* from areas, tree 
where tree.pid = areas.id
)
select @area=isnull(@area,'')+area from tree order by id 
select area= @area
end 
go
--exec sp_helptext 'sp_getareastr'
--go
exec sp_getareastr 28
go

查询结果:中国安徽省宿州市灵璧县

所用表结构:

部分数据:

以上所述是小编给大家介绍的sql server 树形表非循环递归查询的实例详解的相关知识,希望对大家有所帮助

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网