【MySQL】MySQL存储过程从一张表查数据插入另一张表

测试表
CREATE TABLE `demo_test` (
  `ID` varchar(64) NOT NULL,
  `name` varchar(64) DEFAULT NULL,
  `age` varchar(64) DEFAULT NULL,
  PRIMARY KEY (`ID`),
  UNIQUE KEY `DEMO_TEST_ID_uindex` (`ID`)
);

CREATE TABLE `demo_test2` (
  `other_info` varchar(255) DEFAULT NULL
);

demo_test循环插入随机字符
-- 如果存在就删除
drop procedure if exists proc_insert;
create procedure proc_insert()
begin
    -- 定义变量
    DECLARE id VARCHAR(64);
    DECLARE name VARCHAR(64);
    DECLARE age VARCHAR(64);
    DECLARE i INT DEFAULT 1;
    -- 循环插入五条
    WHILE i <= 5
        DO
            SET id = SUBSTRING(MD5(RAND()), 1, 28);
            SET name = SUBSTRING(MD5(RAND()), 1, 5);
            SET age = SUBSTRING(MD5(RAND()), 1, 5);
            INSERT INTO demo_test
            VALUES (id, name, age);
            SET i = i + 1;
        END WHILE;
end;
-- 调用
call proc_insert();

常用函数

  • concat() 拼接字符串函数
  • rand() 生成随机数带小数点函数
  • floor() 取整函数
  • subString() 截取字符串函数
查询demo_testid数据,作为参数,循环插入demo_test2
drop procedure if exists proc_insert2;
create procedure proc_insert2()
begin
    declare var1 varchar(128);
    declare flag int default 0;
    --  定义一个游标来记录sql查询的结果
    declare s_list cursor for SELECT id FROM demo_test;
    --  循环结束标识
    declare continue handler for not found set flag = 1;
    --  打开游标
    open s_list;
    --  将游标中的值赋给定义好的变量
    fetch s_list into var1;
    while flag <> 1
        do
            INSERT INTO demo_test2 values (var1);
            --  游标往后移
            fetch s_list into var1;
        end while;
    --  关闭游标
    close s_list;
end;
-- 调用
call proc_insert2();
  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值