测试表
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_test
的id
数据,作为参数,循环插入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();