MySQL觸發器的創建與刪除 下面的文章主要描述的是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觸發器的使用的介紹,望你能有所收獲。