sql中多层循环示例(有游标)

在需求处理中,我们会遇到需要通过SQL多层循环来处理的问题。如:A表中有8条数据,B表中有10条数据,需要实现A表中的每1条数据对应B表中的10条数据,最后就有了80条数据,从而实现一对多的关系。那如何通过循环来处理呢?
    下面就将为你介绍sql中while循环语句和通过游标来实现循环的实例,供你参考,希望对您学习SQL中的循环语句能够有所帮助。
    :示例中A表相当于t_test1,B表相当于t_test2


一、WHILE循环实现
declare @user_tel varchar(20),@contact_tel varchar(20)
declare @i int,@j int,i_max int,@j_max int
select @i=1,@j=1
select @i_max=max(id) from t_test1
select @j_max=max(id) from t_test2

while @i<=@i_max
begin
 select @user_tel=user_tel from t_test1 where id=@i

 while @j<=@j_max
 begin
 select @contact_tel=user_tel from t_test2 where id=@j 
 insert into t_tmp(user_tel,contact_tel,nick_name,update_dt)
 select @user_tel,@contact_tel,'如梦',getdate()
 
 set @j=@j+1
 end
 set @j=1

set @i=@i+1
end


二、游标实现过程
--采用游标来实现循环处理
declare @user_tel varchar(20),@contact_tel varchar(20)
declare cur_test cursor for select user_tel from t_test1
declare @i int,@j_max int,
select @i=1
select @j_max=max(id) from t_test2
open  cur_test
fetch next from cur_test into @user_tel
while  @@fetch_status=0
begin
 
 while @i<=@j_max
 begin
 select @contact_tel=user_tel from t_test2 where id=@i 
 insert into t_tmp(user_tel,contact_tel,nick_name,update_dt)
 select @user_tel,@contact_tel,'如梦',getdate()
 
 set @i=@i+1
 end
 set @i=1

fetch next from cur_test into @user_tel

原文地址:https://www.cnblogs.com/accumulater/p/7999737.html