Can a MySQL trigger simulate a CHECK constraint? [duplicate]

断了今生、忘了曾经 提交于 2019-11-26 07:42:28

问题


This question already has an answer here:

  • CHECK constraint in MySQL is not working 8 answers

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?

Ultimately I want a trigger that copies a CHECK constraint.


回答1:


Try the following syntax

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;



回答2:


when you are updating data :

delimiter $$
create trigger chk_stats1 before update on stats 
  for each row 
   begin  
    if  new.month>12 then
        SIGNAL SQLSTATE '45000'   
        SET MESSAGE_TEXT = 'Cannot add or update row: only';
      end if; 
      end; 
      $$

when you are inserting data :

   delimiter $$
    create trigger chk_stats before insert on stats 
      for each row 
       begin  
      if  new.month>12 then
       SIGNAL SQLSTATE '45000'   
       SET MESSAGE_TEXT = 'Cannot add or update row: only';
       end if; 
    end; 
    $$

these trigger will work as check constraint ,work before insert or update and check month, if month >12 gives error .




回答3:


From MySQL 5.5 onwards, you can use the SIGNAL syntax to return errors from stored procedures such as triggers.



来源:https://stackoverflow.com/questions/9734920/can-a-mysql-trigger-simulate-a-check-constraint

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!