1. 程式人生 > 其它 >mysql詳解9:觸發器和事件

mysql詳解9:觸發器和事件


觸發器是在插入 更新 刪除語句前後自動執行的sql程式碼
保證資料一致性
DELIMITER $$
CREATE TRIGGER payment_after_insert
After INSERT ON payments
for EACH row
BEGIN
UPDATE invoices
set payment_total payment_total+NEW.amout
where invoice_id =NEW.invoice_id;
END $$

NEW 返回新增的行
OLD 在更新和刪除時候用 返回更新前的行 及對應數值
DELIMITER $$
CREATE TRIGGER payments_after_delete
AFTER DELETE ON payments
FOR EACH ROW
BEGIN
UPDATE invoices
set payment_total =payment_total-OLD.amount
where invoice_id =OLD.invoice_id;
END $$

DELITER;

檢視觸發器
show TRIGGER 顯示所有的觸發器
show TRIGGER LIKE 'payments%'

刪除觸發器
DROP TRIGGER IF EXISTS payment_after_insert

使用觸發器進行審計
操作記錄
DELIMITER $$

DROP TRIGGER IF EXISTS payments_after_delete
CREATE TRIGGER payments_after_delete
AFTER DELETE ON payments
FOR EACH ROW
BEGIN
UPDATE invoices
set payment_total =payment_total-OLD.amount
where invoice_id =OLD.invoice_id;
INSERT INTO payment_audit
values (OLD.client_id,OLD.date,OLD.amount,'delete',NOW());
END $$
DELITER;

事件是根據計劃執行的任務或一堆sql程式碼 定時任務
show variables like 'event%';
set global event_scheduler=on;
--定義一個定時任務
DELIMITER $$
CREATE EVENT hourly_update_member
on SCHEDULE
-- at "2021-07-30"
EVERY 1 hour STARTS '2021-01-01' ENDS '2021-12-31'
do begin
update member set sex=sex+1
where `year` < now() - INTERVAL 1 year;
-- 超過一年的記錄
end $$
DELIMITER;

SHOW EVENTS;
DROP EVENT IF EXISTS hourly_update_member;
alter 和 create 的語法相同
ALTER EVENT hourly_update_member DISABLE;//ENABLE 事件可以暫時啟用禁用