觸發器的型別

定時

有兩個觸發動作時間修飾符:

  • BEFORE 觸發器在執行請求之前啟用,
  • AFTER 在變化後引發火災。

觸發事件

觸發器有三個事件可以附加到:

  • INSERT
  • UPDATE
  • DELETE

在 Insert 觸發器示例之前

DELIMITER $$

CREATE TRIGGER insert_date 
    BEFORE INSERT ON stack
    FOR EACH ROW
BEGIN
        -- set the insert_date field in the request before the insert
    SET NEW.insert_date = NOW();
END;

$$
DELIMITER ;

在 Update 觸發示例之前

DELIMITER $$

CREATE TRIGGER update_date 
    BEFORE UPDATE ON stack
    FOR EACH ROW
BEGIN
        -- set the update_date field in the request before the update
    SET NEW.update_date = NOW();
END;

$$
DELIMITER ;

刪除觸發器示例後

DELIMITER $$

CREATE TRIGGER deletion_date 
    AFTER DELETE ON stack
    FOR EACH ROW
BEGIN
        -- add a log entry after a successful delete
    INSERT INTO log_action(stack_id, deleted_date) VALUES(OLD.id, NOW());
END;

$$
DELIMITER ;