Sql 递归查询

来源:互联网 发布:淘宝网男式手提包 编辑:程序博客网 时间:2024/05/17 01:59

--创建查询函数  
  create   function   f_id(  
  @id   int--要查询的id  
  )returns   @re   table(id   int,level   int)  
  as  
  begin  
  declare   @l   int  
  set   @l=0  
  insert   @re   select   id,@l  
  from   表    
  where   上级id=@id  
  while   @@rowcount>0  
  begin  
  set   @l=@l+1  
  insert   @re   select   a.id,@l  
  from   表   a   join   @re   b   on   a.上级id=b.id   and   b.level=@l-1  
  end  
  return  
  end  
  go  
   
  --调用函数进行查询  
  select   a.*   from   表   a   join   f_id(35)   b   on   a.id=b.id