1、查看事件状态
SELECT @@event_scheduler; 或 show VARIABLES LIKE '%sche%';
2.创建存储过程
示例一批量新增:
delimiter |
drop procedure if exists batch_insert_test_proce;
create procedure batch_insert_test_proce()
begin
DECLARE num INT;
SET num =1;
REPEAT
INSERT into del_info_test(id ,name,value,createTime)VALUES(replace(uuid(),'-',''),'zhangsan','lisi',now());
SET num = num +1;
UNTIL num >1000000
END REPEAT;
end |
delimiter ;
实例二批量删除:
delimiter |
drop procedure if exists batch_del_test_proce;
create procedure batch_del_test_proce()
begin
DECLARE done INT;
DECLARE sumNum int;
DECLARE COUNT int;
SELECT count(1) into sumNum from del_info_test where CREATEtime<NOW();
SET COUNT=sumNum/10000;
SET done =0;
REPEAT
DELETE from del_info_test where CREATEtime<NOW() LIMIT 10000;
SET done = done +1;
UNTIL done >COUNT
END REPEAT;
end |
delimiter ;
3.创建定时器
drop event if exists DEL_INFO_FROM_INFO_TEST_EVERYDAY;
CREATE EVENT IF NOT EXISTS
DEL_INFO_FROM_INFO_TEST_EVERYDAY
ON SCHEDULE EVERY 1 MINUTE STARTS '2017-01-09 14:15:00'
ON COMPLETION PRESERVE
ENABLE
COMMENT '批量删除数据'
DO CALL batch_del_test_proce;
演示例子2:定时删除三个月前的历史数据(每天依次删除)
---轮循删除定时器
drop event if exists waybill_del_procedure;
create event waybill_del_procedure
on schedule every 1 DAY STARTS '2017-01-17 20:00:00'
on completion preserve ENABLE
do call batch_del_cx_waybill_by_day();
------运单表按天轮循删除存储过程
delimiter |
drop procedure if exists batch_del_cx_waybill_by_day;
create procedure batch_del_cx_waybill_by_day()
begin
DECLARE mindate TIMESTAMP;
DECLARE startDate TIMESTAMP;
DECLARE nextDate TIMESTAMP;
DECLARE endDate TIMESTAMP;
SELECT DATE(min(UPDATETIME)) INTO mindate from cx_waybill;
SET startDate=mindate;
SET nextDate=date_add(startDate, INTERVAL 1 day);
SET endDate=DATE(SUBDATE(NOW(),INTERVAL 3 month));
REPEAT
DELETE from cx_waybill where UPDATETIME>=startDate and UPDATETIME<=nextDate and UPDATETIME<endDate ;
SET startDate = date_add(startDate, INTERVAL 1 day);
SET nextDate=date_add(startDate, INTERVAL 1 day);
IF curtime()>'06:00:00' THEN
SET startDate =endDate;
END IF;
UNTIL startDate >=endDate
END REPEAT;
end |
delimiter ;