時間到數據庫自動更新狀態

在MySQL中實現根據時間字段自動更改狀態字段

  • 首先定義update_conference_status過程,判斷系統時間與start_time和end_time的關係,根據這兩個字段調整status字段的狀態。
DELIMITER |

DROP PROCEDURE IF EXISTS update_conference_status |

CREATE PROCEDURE update_conference_status()

BEGIN
    IF exists (select id from conference where `status`='1' and SYSDATE()>=start_time) THEN
            update conference set `status`='2'
            where id in  (select id from (select id from conference where `status`='1' and SYSDATE()>=start_time) as tmp1);
    END IF;

    IF exists (select id from conference where `status`='2' and SYSDATE()>=end_time) THEN
            update conference set `status`='0'
            where id in (select id from (select id from conference where `status`='2' and SYSDATE()>=end_time) as tmp2);
    END IF;
END

 |

DELIMITER;
  • 設置事件,每隔一分鐘調用一次update_conference_status過程。事件的觸發事件可以根據情況而定。
DELIMITER //
CREATE EVENT  event_conference_status
ON SCHEDULE EVERY 1 minute  do
begin
call update_conference_status();
end //
DELIMITER;
  • 最後要保證MySQL支持事件的運行。
SET GLOBAL event_scheduler = ON

ALTER EVENT event_conference_status ON  
COMPLETION PRESERVE ENABLE;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章