当前位置: 代码迷 >> Sql Server >> 关于一个表查询的有关问题
  详细解决方案

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

热度:61   发布时间:2016-04-27 17:43:34.0
关于一个表查询的问题
有这样一个表
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 [email protected]

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

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

go

--调用
exec pr_Tree 1

--ps:未测试
  相关解决方案