zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    Troubleshooting MySQL Memory Usage
    Innodb Log checkpointing 和 dirty Buffer pool pages的关系
    MySQL pager 命令有趣的用法
    测定INNODB REDO LOGS的写入量
    max_allowed_packet & Mysqldump
    链接MyISAM文件
    RFID常识
    C++的程序的文件结构(zt)
    使用C#开发ActiveX控件(zt)
    RFID自动识别术语解释(zt)
  • 原文地址:https://www.cnblogs.com/accumulater/p/7999737.html
Copyright © 2011-2022 走看看