1. 創建存儲過程,具體代碼如下
CREATE DEFINER=`root`@`localhost` PROCEDURE `p_cal_count`( ) BEGIN /*--------------------------------------------------------- -- 庫\表:`beststock`.`t_count` -- 功能: 定期統計各表的數據量 -- 入參: -- 出參: -- added by Bruce He 7/21/2020 -- modified by -----------------------------------------------------------*/ /*用於判斷是否結束循環*/ declare done int default 0; /*存儲表名稱的變量*/ declare curtable VARCHAR(200); /*獲取所有符合條件的表名稱,並存入變量 tbs_list*/ declare tbs_list cursor for select table_name from information_schema.`TABLES` where table_schema='beststock' and (table_name like 'ts%' or table_name like 'rim%'); /*定義 設置循環結束標識done值怎么改變 的邏輯*/ declare continue handler for not found set done =1; open tbs_list; /* 循環開始 */ REPEAT fetch tbs_list into curtable; if not done then /* 初始化 0 */ set @v_count = 0; /* 動態語句執行 */ set @sqlscript = concat('select count(1) into @v_count from ', curtable); prepare tem from @sqlscript; execute tem; insert into beststock.t_count (tablename, count, date) values (curtable, @v_count, CURRENT_DATE); deallocate prepare tem; end if; UNTIL done END REPEAT; close tbs_list; END
2. 開啟定時任務;
-- 查看定時任務是否開啟;ON 開啟, OFF 未開啟 show variables like '%schedule%'; -- 開啟定時任務 set global event_scheduler = 1;
3. 設置定時任務事件