sql中多层循环示例(有游标)
2017-12-07 16:30
441 查看
在需求处理中,我们会遇到需要通过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
下面就将为你介绍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
相关文章推荐
- sql循环嵌套、游标使用、循环结果集示例
- SQL游标(cursor)详细说明及内部循环使用示例
- SQL SERVER中SQL中游标嵌套循环的示例
- SQL游标(cursor)详细说明及内部循环使用示例
- SQL中的循环、for循环、游标
- 用SQL游标遍历循环数据的方法
- SQL循环+游标
- 使用游标循环进行SQL更新插入的SQL语句
- SQL双重游标(双重循环)--笔记
- SQL中的循环、for循环、游标
- SQL 游标示例
- 用SQL游标遍历循环数据的方法
- 循环执行sql语句时报 ORA-01000 maximum open cursors exceeded 超出打开游标的最大数的原因和解决方案
- 用SQL游标遍历循环数据的方法
- sql 游标 跳出循环 和进入下一个循环
- 游标遍历所有数据库循环执行修改数据库的sql命令
- SQL中的循环、for循环、游标
- C#保留2位小数几种场景总结 游标遍历所有数据库循环执行修改数据库的sql命令 原生js轮盘抽奖实例分析(幸运大转盘抽奖) javascript中的typeof和类型判断
- MySQL存储过程中游标循环的跳出和继续操作示例