關(guān)鍵字: MySQL 觸發(fā)器 1、創(chuàng)建觸發(fā)器:
語法:
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
以上的例子是錯(cuò)誤的, 讓本表進(jìn)行觸發(fā)時(shí)進(jìn)行更新會(huì)讓程序進(jìn)入死循環(huán)。
系統(tǒng)會(huì)報(bào)這樣的錯(cuò)誤:it is already used by statement which invoked this stored function/trigger.
應(yīng)該改成以下語句:
CREATE TRIGGER SetUserHome before insert ON users
FOR EACH ROW
BEGIN
set New.homeLocationX = 128;
set New.homeLocationY = 128;
set New.homeLocationZ=30;
END
大寫的為關(guān)鍵字
trigger_name:觸發(fā)器的名字,我常用的命名規(guī)則t_name_tableName_(b|a)(i|u|d),t:觸發(fā)器標(biāo)識(shí),name:英文名,tableName:表名,b(BEFORE):標(biāo)識(shí)是觸發(fā)事件之前,a(AFTER):標(biāo)識(shí)觸發(fā)事件之后,i(insert):標(biāo)識(shí)insert事件,u(update):標(biāo)識(shí)update事件,d(delete):標(biāo)識(shí)delete事件;
trigger_time:觸發(fā)時(shí)間(BEFORE或AFTER)
trigger_event:事件名(insert或update或delete)
tbl_name:表名(必須是永久性表)
trigger_stmt:執(zhí)行語句(可以是復(fù)合語名),使用別名OLD和NEW,能夠引用與觸發(fā)程序相關(guān)的表中的列。
2、刪除解發(fā)器
語法:
DROP TRIGGER [schema_name.]trigger_name;
注意:以上操作均需SUPER權(quán)限
示例:
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 ; 本文出自:億恩科技【1tcdy.com】
服務(wù)器租用/服務(wù)器托管中國五強(qiáng)!虛擬主機(jī)域名注冊頂級提供商!15年品質(zhì)保障!--億恩科技[ENKJ.COM]
|