时间:2021-07-01 10:21:17 帮助过:35人阅读
下面的文章主要描述的是MySQL触发器的正确创建步骤,MySQL触发器的删除,你如果对MySQL触发器的正确创建步骤,MySQL触发器的删除有兴趣的话你就可以点击以下的文章进行观看了。 1、创建MySQL触发器: 语法: CREATETRIGGERtrigger_nametrigger_timetrigger_eve
下面的文章主要描述的是MySQL触发器的正确创建步骤,MySQL触发器的删除,你如果对MySQL触发器的正确创建步骤,MySQL触发器的删除有兴趣的话你就可以点击以下的文章进行观看了。
1、创建MySQL触发器:
语法:
- 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:MySQL触发器标识,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 sumcommentsumcomment=sumcomment+1,sumconsumesumconsume=sumconsume+NEW.consume,sumservicesumservice=sumservice+NEW.service, sumroomsumroom=sumroom+NEW.room,sumentironsumentiron=sumentiron+NEW.entironment,totaltotal=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 sumcommentsumcomment=sumcomment-1,sumconsumesumconsume=sumconsume-NEW.consume,sumservicesumservice=sumservice-NEW.service, sumroomsumroom=sumroom-NEW.room,sumentironsumentiron=sumentiron-NEW.entironment,totaltotal=total-(NEW.service+NEW.room+NEW.entironment) WHERE hotel_id=NEW.hotel_id;
- END IF;
- END;//
- delimiter ;
以上的相关内容就是对MySQL触发器的使用的介绍,望你能有所收获。