博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
sql中多层循环示例(有游标)
阅读量:6654 次
发布时间:2019-06-25

本文共 1274 字,大约阅读时间需要 4 分钟。

在需求处理中,我们会遇到需要通过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 

 while @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=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  
 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

你可能感兴趣的文章
Tomcat中server.xml文件内各节点详解
查看>>
SSH远程访问及控制
查看>>
jquery javascript iframe操作
查看>>
【原创】一路成长一路歌
查看>>
hello
查看>>
debian 安装配置heartbeat
查看>>
解决linux的-bash: ./xx: Permission denied
查看>>
Ubuntu14.10 remove ibus 之后
查看>>
Spring第一天
查看>>
springMVC笔记系列(20)——控制器实现详解(下)
查看>>
nodjs 生产环境及升级问题
查看>>
JS判断客户端是否是iOS或者Android手机移动端
查看>>
laravel 常用的第三方扩展包
查看>>
php超时时间说明
查看>>
spring cron表达式及解析过程
查看>>
嵌入式Linux加快物联网开发速度的方案研究
查看>>
加号+和减号-
查看>>
详解Mysql分布式事务XA(跨数据库事务)
查看>>
2018年,成功的创业公司网站是怎么设计的?
查看>>
MySQL 创始人:写代码比打游戏还爽,程序员应该多泡开源社区
查看>>