Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I define multiple events in one Trigger declaration in mysql?

Here is my requirement, I have a mysql table on which any change (insert/delete/update) should be handled in exactly same way. According to mysql documentation create trigger syntax is as follows:

    CREATE
     [DEFINER = { user | CURRENT_USER }]
     TRIGGER trigger_name
     trigger_time **trigger_event**
     ON tbl_name FOR EACH ROW
     trigger_body

When I'm trying to put more than one event, its throwing syntax error. One solution is I can write one procedure and 3 triggers (one for each event) and call the same procedure from all the triggers.

Is there any sophisticated solution for this ??

like image 752
Silent_Rebel Avatar asked Aug 30 '13 05:08

Silent_Rebel


People also ask

Can we create more than one trigger of same event on same table?

You can create multiple triggers for the same subject table, event, and activation time. The order in which those triggers are activated is the order in which the triggers were created.

How many triggers are allowed in MySQL?

There are 6 different types of triggers in MySQL: 1. Before Update Trigger: As the name implies, it is a trigger which enacts before an update is invoked.

How do I create a multiple trigger in SQL?

Put a slash '/' as the first character on a blank line between each trigger statement. This is the SQL*PLUS equivalent of 'go'.

What is the order of execution if we have multiple triggers for the same event on the same table?

The order of execution isn't guaranteed when having multiple triggers for the same object due to the same event. For example, if you have two before insert triggers for Case, and a new Case record is inserted that fires the two triggers, the order in which these triggers fire isn't guaranteed.


1 Answers

No. In MySQL, a trigger is for a single trigger_event. A trigger has to be either BEFORE or AFTER and one of INSERT, UPDATE, DELETE.

If we have lots of logic that is shared across the trigger events (logic that would need to be duplicated in multiple triggers), we can write/create a PROCEDURE to encapsulate that logic, and call that procedure from the body of multiple triggers.

like image 193
spencer7593 Avatar answered Sep 20 '22 15:09

spencer7593