Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use a trigger to stop an insert or update

Tags:

mysql

triggers

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?

like image 524
Ryan Avatar asked Apr 16 '12 03:04

Ryan


People also ask

How does trigger prevent insertion?

DELIMITER // CREATE TRIGGER yourTriggerName BEFORE INSERT ON yourTableName FOR EACH ROW BEGIN yourCondition THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'anyMessageToEndUser'; END // DELIMITER ; Now, create a trigger that would prevent to insert a record in the table on some condition.

How do you determine if trigger is insert or update or DELETE?

Triggers have special INSERTED and DELETED tables to track "before" and "after" data. So you can use something like IF EXISTS (SELECT * FROM DELETED) to detect an update. You only have rows in DELETED on update, but there are always rows in INSERTED . Look for "inserted" in CREATE TRIGGER.

How can create trigger on insert update and DELETE in SQL Server?

Introduction to SQL Server CREATE TRIGGER statementThe CREATE TRIGGER statement allows you to create a new trigger that is fired automatically whenever an event such as INSERT , DELETE , or UPDATE occurs against a table. In this syntax: The schema_name is the name of the schema to which the new trigger belongs.

How do I stop a trigger in MySQL?

You can disable a trigger temporarily using the DISABLE TRIGGER statement. Disable trigger does not delete the trigger. The trigger exists in the current database but it doesn't fire. In the above syntax, trigger_name is the name of the trigger to be disabled under the schema_name schema.


2 Answers

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.

like image 108
Naveen Kumar Avatar answered Oct 04 '22 15:10

Naveen Kumar


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.

like image 43
bradoaks Avatar answered Oct 04 '22 15:10

bradoaks