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

Solution 1:

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 .

Solution 2:

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

Solution 3:

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;