SQL递归函数用于树的遍历

Code
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO



ALTER      FUNCTION   dbo.FUNC_GET_Edition(@area_id   int,@level_num   int =-1)         
  
RETURNS     @rt_table   table(   
  ProductID   
int,   
  ProductName   
nvarchar(50)   
  )   
  
AS       
  
BEGIN   
  
declare   @tep_name   varchar(50),   
  
@tep_id   int,   
  
@sub_count   int   
    
  
declare   c1   cursor   for   
  (   
  
select   productid,productname  from   product   where   parentid   =   @area_id   
  )   
                    
if   @level_num=0   
begin   
  
insert   into   @rt_table(ProductID,ProductName)     
  
select   productid,productname  from   product   where   productid   =   '000'   
  
end   
    
  
open   c1   
    
  
fetch   c1   into   @tep_id,@tep_name   
  
select   @sub_count   =   0   
  
while   @@fetch_status>=0   
  
begin   
  
select   @sub_count=count(*)   from   product   where   parentid   =   @tep_id   
    
  
insert   into   @rt_table(ProductID,ProductName)values(@tep_id,@tep_name)   
    
  
if   @sub_count>0   
  
begin   
  
insert   into   @rt_table(ProductID,ProductName)     
  
select   ProductID,ProductName     from   dbo.FUNC_GET_Edition(@tep_id,1)   
  
end     
  
FETCH   NEXT   FROM   c1   INTO   @tep_id,@tep_name   
  
end   

  
close   c1   
  
deallocate   c1   
    
  
return     
  
END  



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

转载于:https://www.cnblogs.com/reommmm/archive/2008/04/23/1167291.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值