Suppose we have a database with a table that stores company employee data. If someone does a change to this table, and specifically change an employee's last name, we will be able to audit this through another table called audit_employees. Who will fill the employee_auditory table is our sample trigger that will be executed BEFORE any UPDATE in the Employees table.
== Creating the tables that will be used in this example ==
Employee table
CREATE TABLE 'empregados' (
'id_empregado' int(11) NOT NULL,
'sobrenome' varchar(50) NOT NULL,
'nome' varchar(50) NOT NULL,
'email' varchar(100) NOT NULL,
'cargo' varchar(50) NOT NULL,
PRIMARY KEY ('id_empregado')
)
Audit Employees table
CREATE TABLE empregados_auditoria (
id int(11) NOT NULL AUTO_INCREMENT,
id_empregado int(11) NOT NULL,
sobrenome varchar(50) NOT NULL,
modificadoem datetime DEFAULT NULL,
acao varchar(50) DEFAULT NULL,
PRIMARY KEY (id)
)
== Creating our example Trigger ==
DELIMITER $$
CREATE TRIGGER antesDeUpdate_empregados
BEFORE UPDATE ON empregados
FOR EACH ROW BEGIN
INSERT INTO empregados_auditoria
SET acao = 'update',
id_empregado = OLD.id_empregado,
sobrenome = OLD.sobrenome,
modificadoem = NOW(); END$$
DELIMITER ;
== Testing the operation of our example Trigger ==
As our trigger is called only when an UPDATE is made in the employee table, and this table is currently empty, we need to include at least one record in it:
INSERT INTO 'empregados' ('id_empregado', 'sobrenome', 'nome', 'email', 'cargo') VALUES ('1', 'Silva', 'Ciclano', '[email protected]', 'Programador');
Now we need to execute an UPDATE that modifies an employee's last name before the beforeUpdate_employed trigger is executed:
UPDATE empregados SET sobrenome = 'Santana' WHERE id_empregado = 1;
If we execute a SELECT in the table employees we will be able to see the name of the employee that we register and then we change:
SELECT * FROM empregados;
In order to make sure that the trigger was executed successfully, we just need to query the employee_auditoria table and we will see that the trigger has automatically inserted a record into this table:
SELECT * FROM empregados_auditoria;
You can already have an idea like this.