如何在mysql中强制执行约束? [英] how to enforce a constraint in mysql?

查看:55
本文介绍了如何在mysql中强制执行约束?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表 T,其中包含两个整数类型的字段 A 和 B.

I have a table T with two fields A and B of type integer.

现在我想强制 A 小于或等于 B.

Now I want to enforce that A is smaller or equal to B.

我是否必须创建一个插入/更新之前"的触发器?

Do I have to create a "before insert/update"-trigger?

如果是,那么如何使触发器失败?

And if yes then how do I make the trigger fail?

推荐答案

您可以在应用程序代码中执行此操作,但通过触发器在数据库中执行此操作最安全.

You could do it in your application code, but it's safest to do it in the database via a trigger.

为防止插入成功,请在触发器中生成错误.我们这样做:

To prevent the insert from succeeding, generate an error in your trigger. We do something like this:

CREATE TRIGGER `t_insert`
BEFORE UPDATE ON `t`
FOR EACH ROW
  BEGIN
    IF new.A > new.B THEN
      CALL NONEXISTENT_PROC()
    END IF;
  END

这篇关于如何在mysql中强制执行约束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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