数据库中触发器before与after认识
Before与After区别:
before:(insert、update)可以对new进行修改,after不能对new进行修改,两者都不能修改old数据。
对于INSERT语句, 只有NEW是合法的;
对于DELETE语句,只有OLD才合法;
对于UPDATE语句,NEW、OLD可以同时使用。
例子如下:
1 mysql> select * from t1; 2 +----+-------+ 3 | id | name | 4 +----+-------+ 5 | 1 | zhang | 6 +----+-------+
1 mysql> delimiter // 2 mysql> create trigger tb before update on t1 3 -> for each row 4 -> begin 5 -> set NEW.id=NEW.id+5; 6 -> set NEW.name=upper(NEW.name); 7 -> insert into t2 values(NEW.id,NEW.name); 8 -> end;//
1 分隔符换回分号 2 mysql> delimiter ;
1 mysql> update t1 set name='huang' where id=1; 2 Query OK, 1 row affected (0.01 sec) 3 Rows matched: 1 Changed: 1 Warnings: 0 4 5 mysql> select * from t1 ; 6 +----+-------+ 7 | id | name | 8 +----+-------+ 9 | 6 | HUANG | 10 +----+-------+ 11 1 row in set (0.00 sec)
1 mysql> select * from t2; 2 +----+-------+ 3 | id | name | 4 +----+-------+ 5 | 6 | HUANG | 6 +----+-------+ 7 1 row in set (0.00 sec)
由上可知,如果trigger用的是before,则可以修改new的值,并写入到数据库中
1 同样的代码,把before改成after,则会报错 2 mysql> delimiter // 3 mysql> create trigger ta after update on t1 4 -> for each row 5 -> begin 6 -> set NEW.id=NEW.id+5; 7 -> set NEW.name=upper(NEW.name); 8 -> insert into t2 values (NEW.id,NEW.name); 9 -> end;// 10 ERROR 1362 (HY000): Updating of NEW row is not allowed in after trigger
将after内容改写如下:运行正常
1 mysql> delimiter // 2 mysql> create trigger ta after update on t1 for each row 3 -> begin 4 -> insert into t2 values (OLD.id,NEW.name); 5 -> end;// 6 Query OK, 0 rows affected (0.00 sec) 7 8 mysql> delimiter ; 9 mysql> update t1 set name='chen' where id=6; 10 11 mysql> select * from t1; 12 +----+------+ 13 | id | name | 14 +----+------+ 15 | 6 | chen | 16 +----+------+ 17 1 row in set (0.00 sec) 18 19 mysql> select * from t2; 20 +----+-------+ 21 | id | name | 22 +----+-------+ 23 | 6 | HUANG | 24 | 6 | chen | 25 +----+-------+ 26 2 rows in set (0.00 sec)
总结如下:
after—是在记录操纵之后触发,是先完成数据的增删改,再触发,触发的语句晚于监视的增删改操作,无法影响前面的增删改动作
before—是在记录操纵之前触发,是先完成触发,再增删改,触发的语句先于监视的增删改,我们就有机会判断,修改即将发生的操作,如:我们在触发之前需要判断new值和old值的大小或关系,如果满足要求就触发,不通过就修改再触发;如:表之间定义的有外键,在删除主键时,必须要先删除外键表,这时就有先后之分,这里before相当于设置了断点,我们可以处理删除外键。