while @@rowcount>0 begin set @l=@l+1insert @result select a.p_id,@l from fm_class a where a.id=@idset @pid=(select p_id from fm_class where id=@id) set @id=@pid end 中的insert @result select a.p_id,@l可能插入的不只是一条记录,而 set @pid=(select p_id from fm_class where id=@id) set @id=@pid 只是找到你刚插入的记录中的一条,而其余剩下的刚插入的记录的父亲就找不到了! 你看看这个问题和你的一样的: http://community.csdn.net/Expert/topic/4079/4079662.xml?temp=.7014429
- 好了,不过换了一个写法 -写个函数,方便以后调用CREATE function f_pid(@id int) returns @re table ( p_id int,level int) as begin declare @l int --层次 declare @pid int--父ID set @l=1 --初始层为一 --获取当前ID的父ID set @pid=(select p_id from fm_class where id=@id) --把最近的一个父ID插到表中 insert @re select a.p_id,@l from fm_class a where a.id=@id --把当前ID的父ID作为新的Id set @id=@pid --返回受上一语句影响的行数 while (exists (select p_id from fm_class where id=@id and p_id >0) ) begin set @l=@l+1insert @re select a.p_id,@l from fm_class a where a.id=@idset @pid=(select p_id from fm_class where id=@id) set @id=@pid end return end
begin
set @l=@l+1insert @result select a.p_id,@l
from fm_class a where a.id=@idset @pid=(select p_id from fm_class where id=@id)
set @id=@pid
end
中的insert @result select a.p_id,@l可能插入的不只是一条记录,而
set @pid=(select p_id from fm_class where id=@id)
set @id=@pid
只是找到你刚插入的记录中的一条,而其余剩下的刚插入的记录的父亲就找不到了!
你看看这个问题和你的一样的:
http://community.csdn.net/Expert/topic/4079/4079662.xml?temp=.7014429
好了,不过换了一个写法
-写个函数,方便以后调用CREATE function f_pid(@id int) returns @re table ( p_id int,level int)
as
begin
declare @l int --层次
declare @pid int--父ID
set @l=1 --初始层为一 --获取当前ID的父ID
set @pid=(select p_id from fm_class where id=@id)
--把最近的一个父ID插到表中
insert @re select a.p_id,@l
from fm_class a where a.id=@id
--把当前ID的父ID作为新的Id
set @id=@pid --返回受上一语句影响的行数
while (exists (select p_id from fm_class where id=@id and p_id >0) )
begin
set @l=@l+1insert @re select a.p_id,@l
from fm_class a where a.id=@idset @pid=(select p_id from fm_class where id=@id)
set @id=@pid
end
return
end