首頁 >資料庫 >mysql教程 >MySQL 觸發器中的「FOR EACH ROW」如何運作?

MySQL 觸發器中的「FOR EACH ROW」如何運作?

PHPz
PHPz轉載
2023-09-06 18:17:06726瀏覽

MySQL 触发器中的“FOR EACH ROW”如何工作?

實際上「FOR EACH ROW」意味著更新或刪除的每個符合行。換句話說,我們可以說觸發器並不應用於每一行,它只是說對每個受影響的表行執行觸發器主體。我們可以透過以下範例來說明這一點-

範例

在此範例中,我們建立兩個表,Sample 和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)
Records: 4 Duplicates: 0 Warnings: 0

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)

現在,我們將建立一個觸發器,該觸發器在刪除表“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 ;

現在,以下查詢將從表“Sample”中刪除一些值,並且刪除的行數將儲存在@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)

借助以下查詢,我們可以檢查受刪除影響的行的值,插入到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)

在在上面的範例的幫助下,很明顯「FOR EACH ROW」意味著更新或刪除的每個符合行。

以上是MySQL 觸發器中的「FOR EACH ROW」如何運作?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除