MySQL-觸發器
阿新 • • 發佈:2017-06-12
update 創建 close for 基本語法 rop ... 執行 數據
觸發器:對表進行增刪改操作之後,完成某操作,被稱之為觸發器
1.創建基本語法
1 # 插入前 2 CREATE TRIGGER tri_before_insert_tb1 BEFORE INSERT ON tb1 FOR EACH ROW 3 BEGIN 4 ... 5 END 6 7 # 插入後 8 CREATE TRIGGER tri_after_insert_tb1 AFTER INSERT ON tb1 FOR EACH ROW 9 BEGIN 10 ... 11 END 12 13 # 刪除前 14 CREATE TRIGGER tri_before_delete_tb1 BEFORE DELETE創建觸發器ON tb1 FOR EACH ROW 15 BEGIN 16 ... 17 END 18 19 # 刪除後 20 CREATE TRIGGER tri_after_delete_tb1 AFTER DELETE ON tb1 FOR EACH ROW 21 BEGIN 22 ... 23 END 24 25 # 更新前 26 CREATE TRIGGER tri_before_update_tb1 BEFORE UPDATE ON tb1 FOR EACH ROW 27 BEGIN 28 ... 29 END 30 31 # 更新後 32 CREATE TRIGGERtri_after_update_tb1 AFTER UPDATE ON tb1 FOR EACH ROW 33 BEGIN 34 ... 35 END
1 delimiter // 2 CREATE TRIGGER tri_before_insert_tb1 BEFORE INSERT ON tb1 FOR EACH ROW 3 BEGIN 4 IF NEW. NAME == ‘alex‘ THEN 5 INSERT INTO tb2 (NAME) 6 VALUES 7 (‘aa‘) 8 END// 9 delimiter ;示例:insert之前
1示例:insert之後delimiter // 2 CREATE TRIGGER tri_after_insert_tb1 AFTER INSERT ON tb1 FOR EACH ROW 3 BEGIN 4 IF NEW. num = 666 THEN 5 INSERT INTO tb2 (NAME) 6 VALUES 7 (‘666‘), 8 (‘666‘) ; 9 ELSEIF NEW. num = 555 THEN 10 INSERT INTO tb2 (NAME) 11 VALUES 12 (‘555‘), 13 (‘555‘) ; 14 END IF; 15 END// 16 delimiter ;
特別的:NEW表示即將插入的數據行,OLD表示即將刪除的數據行。
2.刪除觸發器
DROP TRIGGER tri_after_insert_tb1;
3.使用觸發器:一旦對已經生成觸發器的數據表進行觸發條件操作,就會執行觸發器了
insert into tb1(num) values(666)
MySQL-觸發器