现在的位置: 首页 > 综合 > 正文

Sql 递归查询(N层)

2013年03月11日 ⁄ 综合 ⁄ 共 449字 ⁄ 字号 评论关闭
----创建测试数据
if object_id('tbTest') is not null
drop table tbTest
if object_id('spGetChildren') is not null
drop proc spGetChildren
GO
create table tbTest(id int, upperid int)
insert tbTest
select 1, 2 union all
select 3, 2 union all
select 4, 1 union all
select 5, 3
GO
----创建存储过程
create proc spGetChildren @id int
as
declare @t table(id int)
insert @t select id from tbTest where upperid = @id
while @@rowcount > 0
insert @t select a.id from tbTest as a inner join @t as b
on a.upperid = b.id and a.id not in(select id from @t)
select * from @t
GO

抱歉!评论已关闭.