欢迎光临
我们一直在努力

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

使用触发器来停止 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 '45000'
   -> SET MESSAGE_TEXT = 'You can not insert record';
   -> 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)
赞(0) 打赏
未经允许不得转载:码农资源网 » 使用触发器来停止 MySQL 中的插入或更新?
分享到

觉得文章有用就打赏一下文章作者

非常感谢你的打赏,我们将继续提供更多优质内容,让我们一起创建更加美好的网络世界!

支付宝扫一扫打赏

微信扫一扫打赏

登录

找回密码

注册