-- 创建存储过程之前需判断该存储过程是否已存在,若存在则删除
DROP PROCEDURE IF EXISTS sgjan;
-- 创建存储过程
CREATE PROCEDURE sgjan()
BEGIN
-- 定义变量
DECLARE s int DEFAULT 0;
DECLARE p varchar(255);
DECLARE s1 varchar(255);
DECLARE k varchar(256);
DECLARE r varchar(256);
DECLARE u varchar(256);
-- 定义游标,并将sql结果集赋值到游标中
DECLARE report CURSOR FOR
(
SELECT DATE_FORMAT( DATE_SUB( NOW( ), INTERVAL ac DAY ), '%Y-%m-%d' ) AS dateTime FROM
( SELECT @ai := @ai + 1 AS ac FROM
( SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 ) ac1,
( SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 ) ac2,
( SELECT @ai := 0 ) xc0 ) ad
);
-- 声明当游标遍历完后将标志变量置成某个值
DECLARE CONTINUE HANDLER FOR NOT FOUND SET s=1;
-- 打开游标
open report;
-- 将游标中的值赋值给变量,注意:变量名不要和返回的列名同名,变量顺序要和sql结果列的顺序一致
fetch report into u;
-- 当s不等于1,也就是未遍历完时,会一直循环
while s<>1 do
-- 执行业务逻辑
INSERT INTO xhx_project_statistic VALUES
(
(select replace(uuid(),"-","") time),org_id,org_code,device_type,device_use,(select FLOOR(RAND()*10)),
(select FLOOR(RAND()*10)),(select FLOOR(RAND()*10)),(select FLOOR(RAND()*10)),(select FLOOR(RAND()*10)),
(select FLOOR(RAND()*10)),(select FLOOR(RAND()*10)),(select FLOOR(RAND()*10)),u,NULL, NULL,NULL, NULL
); # 往test表添加数据
-- 当s等于1时表明遍历以完成,退出循环
fetch report into u;
end while;
-- 关闭游标
close report;
END;
call sgjan;
select * from xhx_project_statistic;
来源:oschina
链接:https://my.oschina.net/u/4253180/blog/3194769