问题
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