ms-SQL 递归调用

----递归函数--------------------------------------------------------------------------

create  function dbo.f_get_data_by_recursion
 (
  @group_father_id int
 )
  returns @groups_result table (group_id int,group_name varchar(50),group_father_id int,last_count int)
 begin
  declare @count as int
  set @count=1
  
  insert @groups_result select *,@count from groups where group_id=@group_father_id 
  while @@rowcount<>0
  begin
   set @count=@count+1
   insert @groups_result
    select g.group_id,g.group_name,g.group_father_id,@count from groups g,@groups_result gr
     where g.group_father_id=gr.group_id and gr.last_count=@count-1
  end
  return      
 end

GO
View Code
----调用举例--------------------------------------------------------------------------

create table dbo.groups
 (
  group_id int,
  group_name varchar(50),
  group_father_id int
 )


 declare @loop as int
 set @loop =1
 while @loop < 1000
 begin
  insert into groups (group_id,group_name,group_father_id) values (@loop,'name',@loop -1)
  set @loop =@loop +1
 end

set @loop =2001
 while @loop < 2500
 begin
  insert into groups (group_id,group_name,group_father_id) values (@loop,'name',@loop -1)
  set @loop =@loop +1
 end


 select * from groups
 select * from f_get_data_by_recursion(2001)

drop table dbo.groups
 drop function dbo.f_get_data_by_recursion
View Code
原文地址:https://www.cnblogs.com/canyangfeixue/p/3203455.html