page contents

Mysql 使用存储过程动态批量添加数据

精彩内容等你观看!

attachments-2020-08-5p83qIFT5f30a99581e4c.png

循环批量插入数据

-- 创建存储过程
create procedure my_procedure01(in num int(2),out ii int(2))
begin
    declare i int(2) default 0;
    declare str int(2);
    while i < num
    do
        set str = round(rand()*100) + 1;
        insert into p_procedure (name) values (str);
        set i = i + 1;
    end while;
    
    set ii = i;
end;
-- 删除存储过程
drop procedure my_procedure01;
-- 调用存储过程
call my_procedure01(2, @y);
-- 查询存储过程的输出
select @y;

拼接批量插入数据

-- 创建存储过程
create procedure my_procedure02(in num int(2),out ii text)
begin
    declare i int(2) default 0;
    declare str int(2);
    declare data text;
        
    while i < num
    do
        set str = round(rand()*100) + 1;
        set data = concat('(', str, ')');

        -- 存储 alldata 内容的变量必须是全局变量,使用 @ 符修饰
        if @insertData = '' then
            set @insertData = CONCAT_WS(',', data);
        else
            set @insertData = CONCAT_WS(',', @insertData, data);
        end if;

        set i = i + 1;
    end while;
    -- 存储 sql 内容的变量必须是全局变量,使用 @ 符修饰
    set @sql = CONCAT('INSERT INTO p_procedure (name) VALUES ', @insertData);
        
    -- 预处理
    PREPARE ins from @sql;
    EXECUTE ins;
    DEALLOCATE PREPARE ins;
    
    -- 清空全局 @insertData 数据,否则数据会一直追加
    set @insertData = '';

    -- 输出 sql
    set ii = @sql;
        
end;
-- 调用存储过程
call my_procedure02(2, @ii);
-- 查询存储过程的输出
select @ii;
-- 外部重置全局变量
set @insertData = '';
-- 删除存储过程
drop procedure my_procedure02;
-- 存储过程-实例02 - end


**执行的 sql **

attachments-2020-08-FGhslRUY5f30a8545a1d8.png


attachments-2020-08-p4Twv9pw5f30a85ebd337.jpg

  • 发表于 2020-08-10 09:57
  • 阅读 ( 574 )

你可能感兴趣的文章

相关问题

0 条评论

请先 登录 后评论
Pack
Pack

1135 篇文章

作家榜 »

  1. 轩辕小不懂 2403 文章
  2. 小柒 1316 文章
  3. Pack 1135 文章
  4. Nen 576 文章
  5. 王昭君 209 文章
  6. 文双 71 文章
  7. 小威 64 文章
  8. Cara 36 文章