Suppose we have a database with a table that stores the employee data of the company. If by chance someone makes a modification to this table, and specifically changes an employee’s surname, we will be able to audit it through another table called an employe_audit. Who will fill the table employed_audit is our example 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`)
)
table employed_audit
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 sample trigger ==
Since our Rigger is called only when an UPDATE is done on 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 run an UPDATE that modifies an employee’s surname so that Trigger will be executed beforeDeUpdate_employees:
UPDATE empregados SET sobrenome = 'Santana' WHERE id_empregado = 1;
If we run a SELECT in the employee table we can see the employee name we register and then change:
SELECT * FROM empregados;
To be sure that Trigger was successfully executed, we just need to make a query in the table employed_audit and we will see that Trigger has taken charge of inserting a record in this table automatically:
SELECT * FROM empregados_auditoria;
You can get an idea like that.
it would be good to add what you have already done in your question as it will be easier to formulate an appropriate answer
– Pedro Sanção