时间:2021-07-01 10:21:17 帮助过:26人阅读
关键字: MySQL 触发器 1、创建触发器: 语法: CREATE TRIGGER trigger_name trigger_time trigger_event ON tbl_name FOR EACH
关键字: MySQL 触发器 1、创建触发器:
语法:
CREATE TRIGGER trigger_name trigger_time trigger_event ON tbl_name
FOR EACH ROW
BEGIN
trigger_stmt
END;
CREATE TRIGGER trigger_name trigger_time trigger_event ON tbl_name
FOR EACH ROW
BEGIN
trigger_stmt
END;
例子
CREATE TRIGGER SetUserHome after insert ON users
FOR EACH ROW
BEGIN
update `users` set homeLocationX = 128,
homeLocationY=128, homeLocationZ=30
where uuid = NEW.uuid
END
以上的例子是错误的, 让本表进行触发时进行更新会让程序进入死循环。
系统会报这样的错误:it is already used by statement which invoked this stored function/trigger.
应该改成以下语句:
CREATE TRIGGER SetUserHome before insert ON users
FOR EACH ROW
BEGIN
set New.homeLocationX = 128;
set New.homeLocationY = 128;
set New.homeLocationZ=30;
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 ;