sql 根据根节点遍历所有叶子

不使用CTE也就是with因为限制太多,比如不能使用参数

 

declare @startId int
select @startId = id from externalstatus where statusname = @rootStatusName

declare @backtrace   table(id int,lvl int)  
declare @id int
set @id = @startId
declare   @lvl   int  
set   @lvl=0  
insert   @backtrace   select id, @lvl from externalstatus where id = @id  
while   @@rowcount>0  
begin  
set   @lvl=@lvl+1  
insert   @backtrace   select   [status].id, @lvl  
from   externalstatus   [status],@backtrace   backtrace  
where   [status].pid=backtrace.id    
and   backtrace.lvl=@lvl-1
end

你可能感兴趣的:(sql)