MySQL触发器可以模拟CHECK约束吗? [英] Can a MySQL trigger simulate a CHECK constraint?

查看:407
本文介绍了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约束吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆