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 事件可以暂时启用禁用

上一篇:Create data packages for the data import in Dynamics 365 Finance and Operations from Invoice PDFs


下一篇:SAP MM IV中的Duplicated Invoice Check功能的测试