读书人

关于一个表查询的有关问题

发布时间: 2012-02-02 23:57:14 作者: rapoo

关于一个表查询的问题
有这样一个表
ID自身ID
parentID 父ID

ID parentID
1 0
2 0
3 0
4 1
5 1
6 2
7 3
8 4

要求有这样一个存储过程传入一个ID.得到当前ID自身以及所有子级的行数据
比如传 1 得到
1 0
4 1
5 1
8 4


[解决办法]

create proc pr_Tree
@id int
as
declare @t table(
ID int,
parentID int,
lev int
)
declare @lev int
set @lev=0
insert @t select *,@lev from tablename where id=@id

while exists (select 1 from tablename a,@t t where t.lev=@lev and t.id=a.parentID)
begin
insert @t select *,@lev+1 from tablename a,@t t where t.lev=@lev and t.id=a.parentID
set @lev=@lev+1
end

--显示结果
select id,parentID
from @t

go

--调用
exec pr_Tree 1

--ps:未测试

读书人网 >SQL Server

热点推荐