MySQL触发器的使用

阅读更多
1、创建触发器:
语法:
CREATE TRIGGER trigger_name trigger_time trigger_event ON tbl_name
FOR EACH ROW 
BEGIN
 trigger_stmt
END;

大写的为关键字
trigger_name:触发器的名字,我常用的命名规则t_name_tableName_(b|a)(i|u|d),t:触发器标识,name:英文名,tableName:表名,b(BEFORE):标识是触发事件之前,a(AFTER):标识触发事件之后,i(insert):标识insert事件,u(update):标识update事件,d(delete):标识delete事件;
trigger_time:触发时间(BEFORE或AFTER)
trigger_event:事件名(insert或update或delete)
tbl_name:表名(必须是永久性表)
trigger_stmt:执行语句(可以是复合语名),使用别名OLD和NEW,能够引用与触发程序相关的表中的列。
2、删除解发器
语法:
DROP TRIGGER [schema_name.]trigger_name;
注意:以上操作均需SUPER权限
示例:
DROP TRIGGER t_wiley_hotelComment_bu;
delimiter //
CREATE TRIGGER t_wiley_hotelComment_bu BEFORE UPDATE ON hotel_comment
FOR EACH ROW
BEGIN
    IF OLD.ispass=0 && NEW.ispass=1 THEN
       UPDATE hotel_info SET sumcomment=sumcomment+1,sumconsume=sumconsume+NEW.consume,sumservice=sumservice+NEW.service, sumroom=sumroom+NEW.room,sumentiron=sumentiron+NEW.entironment,total=total+(NEW.service+NEW.room+NEW.entironment) WHERE hotel_id=NEW.hotel_id;
  ELSEIF OLD.ispass=1 && NEW.ispass=0 THEN
     UPDATE hotel_info SET sumcomment=sumcomment-1,sumconsume=sumconsume-NEW.consume,sumservice=sumservice-NEW.service, sumroom=sumroom-NEW.room,sumentiron=sumentiron-NEW.entironment,total=total-(NEW.service+NEW.room+NEW.entironment) WHERE hotel_id=NEW.hotel_id;
  END IF;
END;//
delimiter ;

说明:delimiter 改变语句结束符

你可能感兴趣的:(MySQL)