如何使用事件更新mysql数据并在之后删除事件

时间:2017-01-16 20:09:20

标签: mysql

我有一个看起来像这样的mysql表

| begintime  | endtime  | begindate  | enddate  | state |
+------------+----------+------------+----------+-------+
|  TIME      | TIME     |    DATE    |   DATE   | string|
+------------+----------+------------+----------+-------+

我有这段代码

CREATE EVENT Update
ON SCHEDULE
  EVERY 1 SECOND
DO
  UPDATE tablename SET tablename.state = CASE
   WHEN (SELECT CURRENT_TIME() FROM DUAL)>=tablename.begintime AND (SELECT CURDATE()>= tablename.begindate) THEN "Available"
   WHEN (SELECT CURRENT_TIME() FROM DUAL)>tablename.endtime AND (SELECT CURDATE()= tablename.enddate) THEN "Finished" 
   ELSE "Not Available"
   END

我希望服务器始终检查这些语句是否属实,我不知道如何在以下情况下删除该事件:

WHEN (SELECT CURRENT_TIME() FROM DUAL)>tablename.endtime AND (SELECT CURDATE()= tablename.enddate) THEN "Finished 

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

请尝试这个。

SET GLOBAL event_scheduler = ON;
DROP EVENT IF EXISTS Update1;
CREATE EVENT Update1
ON SCHEDULE
  EVERY 1 SECOND
DO
  UPDATE tablename SET tablename.state = 
  CASE
   WHEN NOW() BETWEEN CONCAT(tablename.begindate,' ',tablename.begintime) AND CONCAT(tablename.enddate,' ',tablename.endtime) THEN "Available"
   WHEN NOW() > CONCAT(tablename.enddate,' ',tablename.endtime) THEN "Finished"
   ELSE "Not Available"
  END;

要在设置为“已完成”后放弃事件,请尝试使用此类

SET GLOBAL event_scheduler = ON;
DROP EVENT IF EXISTS Update1;
DELIMITER //
CREATE EVENT Update1
ON SCHEDULE
  EVERY 1 SECOND
DO BEGIN
    SELECT @begindate := begindate,
           @begintime:= begintime,
           @enddate := enddate,
           @endtime := endtime FROM tablename;
    IF (NOW() BETWEEN CONCAT(@begindate,' ',@begintime) AND CONCAT(@enddate,' ',@endtime)) THEN
        UPDATE tablename SET state = 'Available'; 
    ELSEIF (NOW() < CONCAT(@begindate,' ',@begintime)) THEN
        UPDATE tablename SET state = 'Not Available';
    ELSEIF (NOW() > CONCAT(@enddate,' ',@endtime)) THEN
        UPDATE tablename SET state = 'Finished';
        DROP EVENT IF EXISTS Update1;
    END IF;
END//
DELIMITER ;