Home >Database >Mysql Tutorial >MYSQL存储过程及事件_MySQL

MYSQL存储过程及事件_MySQL

WBOY
WBOYOriginal
2016-06-01 13:04:13795browse

关于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 &#39;C:/\\",@today,".txt&#39;  FIELDS TERMINATED BY &#39;,&#39;;");        
 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 ',' 字段间分割符
OPTIONALLY ENCLOSED BY '"' 将字段包围 对数值型无效
LINES TERMINATED BY '\n' 换行符

下面是创建事件的代码 ,逻辑是从'2014-11-05 09:00:00'开始,每天去执行pro_test()这个过程。

CREATE DEFINER=`root`@`localhost` 
EVENT `NewEvent`
ON SCHEDULE EVERY 1 DAY STARTS &#39;2014-11-05 09:00:00&#39;
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;

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn