在需求处理中,我们会遇到需要通过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 intselect @i=1,@j=1select @i_max=max(id) from t_test1select @j_max=max(id) from t_test2while @i<=@i_max
begin select @user_tel=user_tel from t_test1 wherewhile @j<=@j_max
begin select @contact_tel=user_tel from t_test2 where 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=1set @i=@i+1
end二、游标实现过程--采用游标来实现循环处理declare @user_tel varchar(20),@contact_tel varchar(20)declare cur_test cursor for select user_tel from t_test1declare @i int,@j_max int,select @i=1select @j_max=max(id) from t_test2open cur_testfetch next from cur_test into @user_telwhile @@fetch_status=0begin while @i<=@j_max begin select @contact_tel=user_tel from t_test2 where 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