Use a trigger to stop an insert or update(使用触发器停止插入或更新)
问题描述
既然 MySQL 忽略了检查约束,那么如何使用触发器来阻止插入或更新的发生?
Since MySQL ignores check constraints, how does one go about using a trigger to stop an insert or update from happening?
例如:
表foo有一个属性叫agency,该agency属性只能是1、2、3、4、5.
Table foo has an attribute called agency, and the agency attribute can only be 1, 2, 3, 4, or 5.
delimiter $$
create trigger agency_check
before insert on foo
for each row
begin
if (new.agency < 1 or new.agency > 5) then
#Do nothing?
end if;
end
$$
delimiter ;
或者是否有更好的方法在 MySQL 中进行检查约束?
Or is there a better way to go about doing check constraints in MySQL?
推荐答案
尝试 SIGNAL 语法 - https://dev.mysql.com/doc/refman/5.5/en/signal.html
Try the SIGNAL syntax - https://dev.mysql.com/doc/refman/5.5/en/signal.html
create trigger agency_check
before insert on foo
for each row
begin
if (new.agency < 1 or new.agency >5) then
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'your error message';
end if
end
编辑
根据 Bill Karwin 下面的热门评论更新.
Updated based on popular comment below by Bill Karwin.
这篇关于使用触发器停止插入或更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用触发器停止插入或更新
基础教程推荐
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
- 带更新的 sqlite CTE 2022-01-01
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
- 带有WHERE子句的LAG()函数 2022-01-01
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
- MySQL 5.7参照时间戳生成日期列 2022-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
- 从字符串 TSQL 中获取数字 2021-01-01
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
