15 posts
In order to create a new trigger, you use the CREATE TRIGGER
statement.
Syntax of the CREATE TRIGGER
statement:
CREATE TRIGGER trigger_name trigger_time trigger_event
ON table_name
FOR EACH ROW
BEGIN
...
END;
CREATE TRIGGER
statement. The trigger name should follow the naming convention [trigger time]_[table name]_[trigger event]
, for example before_employees_update
.BEFORE
or AFTER
. You must specify the activation time when you define a trigger. You use the BEFORE
keyword if you want to process action prior to the change is made on the table and AFTER
if you need to process action after the change is made.INSERT
, UPDATE or
DELETE
. This event causes the trigger to be invoked. A trigger only can be invoked by one event. To define a trigger that is invoked by multiple events, you have to define multiple triggers, one for each event.ON
keyword.BEGIN
and END
block. This is where you define the logic for the trigger.Let's create Trigger on the Employee table.
Step 1 : First, create a new table named employees_audit
to keep the changes of the employee
table. The following statement creates the employee_audit
table.
CREATE TABLE employees_audit (
id INT AUTO_INCREMENT PRIMARY KEY,
employeeNumber INT NOT NULL,
lastname VARCHAR(50) NOT NULL,
changedat DATETIME DEFAULT NULL,
action VARCHAR(50) DEFAULT NULL
);
Step 2 : Next, create a BEFORE UPDATE
trigger that is invoked before a change is made to the employees
table.
DELIMITER $$
CREATE TRIGGER before_employee_update
BEFORE UPDATE ON employees
FOR EACH ROW
BEGIN
INSERT INTO employees_audit
SET action = 'update',
employeeNumber = OLD.employeeNumber,
lastname = OLD.lastname,
changedat = NOW();
END$$
DELIMITER ;
Inside the body of the trigger, we used the OLD
keyword to access employeeNumber
and lastname
column of the row affected by the trigger.
Now trigger is created and you can see the triggers in the current database using the following statement.
SHOW TRIGGERS;
Please log in to leave a comment.