Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MySQL

Cơ chế hoạt động của FOR EACH ROW trong trigger MySQL

FOR EACH ROW nghĩa là cho mỗi hàng khớp bị cập nhật hoặc xóa. Nói cách khác, trigger không áp dụng cho từng hàng, mà chỉ nói: thực thi thân trigger cho mỗi hàng bị ảnh hưởng của bảng. Minh họa qua ví dụ:

Ví dụ

Tạo hai bảng Sample và Sample_rowaffected:

mysql> Create table Sample(id int, value varchar(20));
Query OK, 0 rows affected (0.47 sec)
mysql> Insert into Sample(id, value) values(100, 'same'),(101, 'Different'),(500, 'excellent'),(501, 'temporary');
Query OK, 4 rows affected (0.04 sec)
mysql> Select * from Sample;
+------+-----------+
| id   | value     |
+------+-----------+
| 100  | same      |
| 101  | Different |
| 500  | excellent |
| 501  | temporary |
+------+-----------+
4 rows in set (0.00 sec)
mysql> Create table Sample_rowaffected(id int);
Query OK, 0 rows affected (0.53 sec)
mysql> Select Count(*) as 'Rows Affected' from sample_rowaffected;
+---------------+
| Rows Affected |
+---------------+
|             0 |
+---------------+
1 row in set (0.10 sec)

Tạo trigger kích hoạt BEFORE DELETE trên bảng Sample:

mysql> Delimiter //
mysql> Create trigger trigger_before_delete_sample BEFORE DELETE on Sample
    -> FOR EACH ROW
    -> BEGIN
    -> SET @count = if (@count IS NULL, 1, (@count+1));
    -> INSERT INTO sample_rowaffected values (@count);
    -> END ;
    -> //
Query OK, 0 rows affected (0.15 sec)
mysql> Delimiter ;

Xóa một số giá trị từ bảng Sample, số hàng bị xóa lưu vào biến @count:

mysql> Delete from Sample WHERE ID >=500;
Query OK, 2 rows affected (0.11 sec)
mysql> Select @count;
+--------+
| @count |
+--------+
|      2 |
+--------+
1 row in set (0.03 sec)

Kiểm tra số hàng bị xóa đã chèn vào sample_rowaffected:

mysql> Select Count(*) as 'Rows Affected' from sample_rowaffected;
+---------------+
| Rows Affected |
+---------------+
|             2 |
+---------------+
1 row in set (0.00 sec)
mysql> Select * from Sample;
+------+-----------+
| id   | value     |
+------+-----------+
| 100  | same      |
| 101  | Different |
+------+-----------+
2 rows in set (0.00 sec)

Ví dụ trên làm rõ FOR EACH ROW nghĩa là cho mỗi hàng khớp bị cập nhật hoặc xóa.