mysql 循环insert方式

来自:网络
时间:2022-12-27
阅读:
目录

mysql 循环insert

亲测成功!可用,复制即可

DELIMITER ;;
CREATE PROCEDURE test_insert()
BEGIN
DECLARE y TINYINT DEFAULT 1;
WHILE y<10
DO
INSERT INTO sysuser_user_deposit_log(log_id, type, user_id, operator, fee, message, logtime, deposit) VALUES (NULL, 'expense', '4903', 'system', '0.500', '用户抽奖,抽奖单号:1807261600465829', '1532592017', NULL);
SET y=y+1;
END WHILE ;
commit;
END;;
CALL test_insert();

mysql 循环语句

本文总结了mysql常见的三种循环方式:while、repeat和loop循环。还有一种goto,不推荐使用。

一、while循环

delimiter //                            #定义标识符为双斜杠
drop procedure if exists test;          #如果存在test存储过程则删除
create procedure test()                 #创建无参存储过程,名称为test
begin
    declare i int;                      #申明变量
    set i = 0;                          #变量赋值
    while i < 10 do                     #结束循环的条件: 当i大于10时跳出while循环
        insert into test values (i);    #往test表添加数据
        set i = i + 1;                  #循环一次,i加一
    end while;                          #结束while循环
    select * from test;                 #查看test表数据
end
//                                      #结束定义语句
call test();                            #调用存储过程

二、repeat循环

delimiter //                            #定义标识符为双斜杠
drop procedure if exists test;          #如果存在test存储过程则删除
create procedure test()                 #创建无参存储过程,名称为test
begin
    declare i int;                      #申明变量
    set i = 0;                          #变量赋值
    repeat
        insert into test values (i);    #往test表添加数据
        set i = i + 1;                  #循环一次,i加一
    until i > 10 end repeat;            #结束循环的条件: 当i大于10时跳出repeat循环
    select * from test;                 #查看test表数据
end
//                                      #结束定义语句
call test();                            #调用存储过程

三、loop循环

delimiter //                            #定义标识符为双斜杠
drop procedure if exists test;          #如果存在test存储过程则删除
create procedure test()                 #创建无参存储过程,名称为test
begin
    declare i int;                      #申明变量
    set i = 0;                          #变量赋值
    lp : loop                           #lp为循环体名,可随意 loop为关键字
        insert into test values (i);    #往test表添加数据
        set i = i + 1;                  #循环一次,i加一
        if i > 10 then                  #结束循环的条件: 当i大于10时跳出loop循环
            leave lp;
        end if; 
    end loop;
    select * from test;                 #查看test表数据
end
//                                      #结束定义语句
call test();                            #调用存储过程

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

 

返回顶部
顶部