Can a MySQL trigger simulate a CHECK constraint?(MySQL 触发器可以模拟 CHECK 约束吗?)
问题描述
我想在 MySQL 中使用 CHECK 约束,但它不受支持.(与其他 RDBMS 不同,它会理解但不强制执行 CHECK.)
I want to use the CHECK constraint in MySQL, but it is not supported. (Unlike other RDBMS, it will understand but not enforce the CHECKs.)
我已经看到了一些使用触发器的解决方法.但他们倾向于为相关字段设置默认值,而不是返回错误.
I have seen some workarounds with triggers. But they tend to set a default value to the field in question instead of returning an error.
是否可以构造一个触发器,在不满足条件时返回错误?
Is it possible to construct a trigger that returns an error if a condition is not met?
最终我想要一个复制 CHECK 约束的触发器.
Ultimately I want a trigger that copies a CHECK constraint.
推荐答案
试试下面的语法
CREATE TRIGGER mytabletriggerexample
BEFORE INSERT
FOR EACH ROW BEGIN
IF(NEW.important_value) < (fancy * dancy * calculation) THEN
DECLARE dummy INT;
SELECT Your meaningful error message goes here INTO dummy
FROM mytable
WHERE mytable.id=new.id
END IF; END;
这篇关于MySQL 触发器可以模拟 CHECK 约束吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:MySQL 触发器可以模拟 CHECK 约束吗?


基础教程推荐
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
- MySQL 5.7参照时间戳生成日期列 2022-01-01
- 带有WHERE子句的LAG()函数 2022-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
- 从字符串 TSQL 中获取数字 2021-01-01
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
- 带更新的 sqlite CTE 2022-01-01
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01