Trigger

-- Triggers
-- Los triggers son acciones que se ejecutan cuando modificamos datos
-- en una tabla. Se suelen usar para realizar tareas de mantenimiento
-- de integridad que no permite el sql
-- Ya estamos trabajando con programación T-SQL
-- https://dev.mysql.com/doc/refman/8.4/en/triggers.html

-- Los triggers los tenemos en la pestaña 'triggers'
-- son before o update y para insert, update y delete

-- Ejemplos
-- Este hace que cuando borremos un actor, si su id está entre 1 y 20 no nos deja
-- En caso contrario lo inserta en un log
CREATE TRIGGER `sakila`.`actor_BEFORE_DELETE` BEFORE DELETE ON `actor` FOR EACH ROW
BEGIN

if OLD.actor_id between 1 and 20 then
 SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'No puedes borrar';
else
 insert into actor_log(first_name, last_name) values (OLD.first_name, OLD.last_name);
end if;
END

CREATE DEFINER=`root`@`localhost` TRIGGER `sakila`.`payment_BEFORE_INSERT` BEFORE INSERT ON `payment` FOR EACH ROW
BEGIN
if NEW.amount>=10 then
 set NEW.amount=9.99;
end if;
END

CREATE DEFINER = CURRENT_USER TRIGGER `sakila`.`payment_BEFORE_UPDATE` BEFORE UPDATE ON `payment` FOR EACH ROW
BEGIN
if NEW.amount > OLD.amount then
 set NEW.amount=OLD.amount;
end if;
END

Publicado por

Avatar del usuario

Juan Pablo Fuentes

Formador de programación y bases de datos