1. TRIGGER简介 trigger是mysql的触发器,当建立触发器时,会监控特定的事件,当触发时会激活对象,处理trigger_stmt,即要执行的语句。比如表的新增一条记录时,你需要更新记录的值得总和,则可以用trigger来实现。 2. Trigger创建语句 CREATE TRIGGER trig
CREATE TRIGGER trigger_name trigger_time trigger_event ON tbl_name FOR EACH ROW trigger_stmt
CREATE TABLE account (acct_num INT, amount DECIMAL(10,2)); CREATE TRIGGER ins_sum BEFORE INSERT ON account FOR EACH ROW SET @sum = @sum + NEW.amount;
mysql> SET @sum = 0; mysql> INSERT INTO account VALUES(137,14.98),(141,1937.50),(97,-100.00); mysql> SELECT @sum AS 'Total amount inserted';
mysql> delimiter // mysql> CREATE TRIGGER upd_check BEFORE UPDATE ON account -> FOR EACH ROW -> BEGIN -> IF NEW.amount < 0 THEN -> SET NEW.amount = 0; -> ELSEIF NEW.amount > 100 THEN -> SET NEW.amount = 100; -> END IF; -> END;// mysql> delimiter ;
update account set acct_num = 241 where acct_num=141;
show triggers
drop trigger test.ins_sum;
· 如果BEFORE触发程序失败,不执行相应行上的操作。
· 仅当BEFORE触发程序(如果有的话)和行操作均已成功执行,才执行AFTER触发程序。· 对于事务性表,如果触发程序失败(以及由此导致的整个语句的失败),该语句所执行的所有更改将回滚。对于非事务性表,不能执行这类回滚,因而,即使语句失败,失败之前所作的任何更改依然有效。
地址:http://blog.csdn.net/yonggang7/article/details/24552817