關於mysql下的存儲過程以及事件的創建
下面這個存儲過程主要實現的功能就是查詢表裡面半年前的數據,如果有就存到文件,然後將數據刪除。
CREATE DEFINER = `root`@`localhost` PROCEDURE `NewProc`() BEGIN select COUNT(*) INTO @count from S_ACCOUNT where date_add(registerTime, interval 6 month)<=NOW(); IF @count>0 THEN set @today=TIME_TO_SEC(now()); set @select_sql=concat("select * from S_ACCOUNT where date_add(registerTime, interval 6 month)<=NOW() INTO OUTFILE 'C:/\\",@today,".txt' FIELDS TERMINATED BY ',';"); PREPARE charu FROM @select_sql; EXECUTE charu; delete from S_ACCOUNT where date_add(registerTime, interval 6 month)<=NOW() ; commit; END IF; END;FIELDS TERMINATED BY ',' 字段間分割符
下面是創建事件的代碼 ,邏輯是從'2014-11-05 09:00:00'開始,每天去執行pro_test()這個過程。
CREATE DEFINER=`root`@`localhost` EVENT `NewEvent` ON SCHEDULE EVERY 1 DAY STARTS '2014-11-05 09:00:00' ON COMPLETION NOT PRESERVE ENABLE DO call pro_test();
當我們在創建事件的時候有可能會提示事件處於關閉狀態,這個時候就需要手動開啟事件。
首先在sql中查詢計劃事件的狀態:SHOW VARIABLES LIKE 'event_scheduler'
如果返回的是off表示當前是關閉狀態,如果是on當前已經開啟了計劃任務。
在mysql程序的目錄下找到my.ini文件,添加一個項:event_scheduler = 1
保存後重啟mysql服務即可,重啟服務可以在服務管理裡面找到.
也可以用腳本來實現:
mysql event_scheduler
開啟event_scheduler sql指令:
SET GLOBAL event_scheduler = ON;
SET @@global.event_scheduler = ON;
SET GLOBAL event_scheduler = 1;
SET @@global.event_scheduler = 1;
相反,關閉event_scheduler指令:
SET GLOBAL event_scheduler = OFF;
SET @@global.event_scheduler = OFF;
SET GLOBAL event_scheduler = 0;
SET @@global.event_scheduler = 0;