MySQL 5.7.2+ cho phép tạo nhiều trigger cho cùng event và action time trên một bảng. Các trigger kích hoạt tuần tự khi sự kiện xảy ra. Ví dụ:
Ví dụ
Tạo nhiều trigger cho BEFORE UPDATE trên bảng Student_detail:
mysql> Select * from Student_detail;
+-----------+-------------+------------+
| Studentid | StudentName | address |
+-----------+-------------+------------+
| 100 | Gaurav | Delhi |
| 101 | Raman | Shimla |
| 103 | Rahul | Jaipur |
| 104 | Ram | Chandigarh |
| 105 | Mohan | Chandigarh |
+-----------+-------------+------------+
5 rows in set (0.06 sec)
mysql> Delimiter //
mysql> Create Trigger studentdetail_before_update
-> BEFORE UPDATE
-> ON Student_detail
-> FOR EACH ROW
-> BEGIN
-> DECLARE AUSER Varchar(40);
-> SELECT USER() into AUSER;
-> INSERT INTO Student_detail_updated(studentid, Updated_date,Updated_by) values(OLD.studentid,NOW(),AUSER);
-> END; //
Query OK, 0 rows affected (0.17 sec)
mysql> Update student_detail SET Address = 'Ludhiana' Where studentName = 'Ram';
Query OK, 1 row affected (0.15 sec)
Rows matched: 1 Changed: 1 Warnings: 0
Kết quả sau trigger đầu tiên:
mysql> Select * from student_detail_updated; +-----------+---------------------+----------------+ | studentid | Updated_date | Updated_by | +-----------+---------------------+----------------+ | 104 | 2017-11-22 16:17:16 | root@localhost | +-----------+---------------------+----------------+ 1 row in set (0.00 sec)
Tạo trigger thứ hai cùng event/time, dùng FOLLOWS để chạy sau trigger đầu:
mysql> Create Trigger studentdetail_before_update2
-> BEFORE UPDATE
-> ON Student_detail
-> FOR EACH ROW FOLLOWS studentdetail_before_update
-> BEGIN
-> DECLARE AUSER Varchar(40);
-> SELECT USER() into AUSER;
-> INSERT INTO Student_detail_updated(studentid, Updated_date,Updated_by) values(OLD.studentid,NOW(),AUSER);
-> END; //
Query OK, 0 rows affected (0.15 sec)
Cập nhật lại:
mysql> Update Student_detail SET Address = 'Patiala' WHERE studentname = 'Mohan'; Query OK, 1 row affected (0.08 sec)
Kết quả có 2 hàng cho cùng event (hàng 2 từ trigger 1, hàng 3 từ trigger 2):
mysql> Select * from student_detail_updated; +-----------+---------------------+----------------+ | studentid | Updated_date | Updated_by | +-----------+---------------------+----------------+ | 104 | 2017-11-22 16:17:16 | root@localhost | | 105 | 2017-11-22 16:19:28 | root@localhost | | 105 | 2017-11-22 16:19:28 | root@localhost | +-----------+---------------------+----------------+ 3 rows in set (0.00 sec)