Use a trigger to stop an insert or update

2020-01-25 01:53发布

Since MySQL ignores check constraints, how does one go about using a trigger to stop an insert or update from happening?

For example:

Table foo has an attribute called agency, and the agency attribute can only be 1, 2, 3, 4, or 5.

delimiter $$
create trigger agency_check
before insert on foo
for each row
begin
if (new.agency < 1 or new.agency > 5) then

#Do nothing?

end if;
end
$$
delimiter ;

Or is there a better way to go about doing check constraints in MySQL?

2条回答
▲ chillily
2楼-- · 2020-01-25 02:11

If your version of MySQL is older than 5.5, try setting a non-null field of the table to NULL. It is a hack, but it does prevent the update or insert from completing.

The SIGNAL command which Naveen suggests looks great, and I'm looking forward to using it after we upgrade.

查看更多
狗以群分
3楼-- · 2020-01-25 02:27

Try the SIGNAL syntax - https://dev.mysql.com/doc/refman/5.5/en/signal.html

create trigger agency_check
before insert on foo
for each row
begin
  if (new.agency < 1 or new.agency >5) then
    SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'your error message';
  end if 
end

EDIT

Updated based on popular comment below by Bill Karwin.

查看更多
登录 后发表回答