首頁  >  文章  >  資料庫  >  使用觸發器來停止 MySQL 中的插入或更新?

使用觸發器來停止 MySQL 中的插入或更新?

PHPz
PHPz轉載
2023-08-25 20:49:161201瀏覽

使用触发器来停止 MySQL 中的插入或更新?

您需要使用 SIGNAL SQL STATE 指令來停止 MySQL 中的插入或更新。觸發器語法如下:

DELIMITER //
CREATE TRIGGER yourTriggerName BEFORE INSERT ON yourTableName FOR EACH ROW
BEGIN
yourCondition THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'anyMessageToEndUser';
END //
DELIMITER ;

現在,建立一個觸發器,以防止在某些情況下在表中插入記錄。建立觸發器的查詢如下:

mysql> DELIMITER //
mysql> CREATE TRIGGER InsertPreventTrigger BEFORE INSERT ON Insert_Prevent
   -> FOR EACH ROW
   -> BEGIN
   -> IF(new.Id < 1 or new.Id > 5) THEN
   -> SIGNAL SQLSTATE &#39;45000&#39;
   -> SET MESSAGE_TEXT = &#39;You can not insert record&#39;;
   -> END IF;
   -> END //
Query OK, 0 rows affected (0.20 sec)
mysql> DELIMITER ;

每當插入小於0或大於5的記錄時,上面的觸發器將停止插入。

現在讓我們先建立一個表格。建立表格的查詢如下:

mysql> create table Insert_Prevent
   -> (
   -> Id int
   -> );
Query OK, 0 rows affected (0.62 sec)

現在插入小於0或大於5的記錄。這將導致錯誤訊息,因為每當插入小於0或大於5的記錄時,都會建立觸發器來停止插入。錯誤訊息如下:

mysql> insert into Insert_Prevent values(0);
ERROR 1644 (45000): You cannot insert record
mysql> insert into Insert_Prevent values(6);
ERROR 1644 (45000): You cannot insert record

如果插入1到5之間的記錄,不會出現任何錯誤。它不會阻止記錄插入,因為如上所述,我們建立觸發器來插入 1 到 5 之間的記錄。插入記錄的查詢如下:

mysql> insert into Insert_Prevent values(1);
Query OK, 1 row affected (0.20 sec)
mysql> insert into Insert_Prevent values(5);
Query OK, 1 row affected (0.17 sec)
mysql> insert into Insert_Prevent values(2);
Query OK, 1 row affected (0.11 sec)
mysql> insert into Insert_Prevent values(3);
Query OK, 1 row affected (0.23 sec)

使用 select 語句顯示表中的所有記錄。查詢如下:

mysql> select *from Insert_Prevent;

以下是輸出:

+------+
| Id   |
+------+
|    1 |
|    5 |
|    2 |
|    3 |
+------+
4 rows in set (0.00 sec)

以上是使用觸發器來停止 MySQL 中的插入或更新?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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