Mysql trigger to be fired whenever a field is edited

Asked

Viewed 541 times

1

Good colleagues, I have a problem I haven’t solved yet. I intend to create a Rigger that whenever the product quantity column undergoes an update it triggers an action to another table, to allow the user to know that a particular product has suffered an increase or decrease. Is it possible in mysql? If yes how, what would be the logic?

Table that will be updated in the quantity field

'producto', 'CREATE TABLE `producto` (\n  
idProducto` int(11) NOT NULL AUTO_INCREMENT,\n 
 `artigo` int(11) NOT NULL,\n  `data` datetime NOT NULL,\n 
 `tipoProducto` varchar(50) NOT NULL,\n 
 `descricao` mediumtext NOT NULL,\n  
`quantidade` int(11) NOT NULL,\n  
`validade` date DEFAULT NULL,\n 
 PRIMARY KEY (`idProducto`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8'

Table in which action will be fired

`'entrada_producto', 'CREATE TABLE `entrada_producto` (\n  
`idEntrada` int(11) NOT NULL AUTO_INCREMENT,\n 
 `idProducto` int(11) DEFAULT NULL,\n 
 `dataEntrada` datetime DEFAULT NULL,\n 
 `quantidade_entrada` int(11) DEFAULT NULL,\n 
 `descricao` mediumtext,\n
 PRIMARY KEY (`idEntrada`),\n  KEY `idProducto` (`idProducto`),\n  CONSTRAINT `entrada_producto_ibfk_1` FOREIGN KEY (`idProducto`) REFERENCES `producto` (`idproducto`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8'`

1 answer

0

You can make a Rigger as below:

DELIMITER $$
CREATE TRIGGER produto_update
AFTER UPDATE
   ON producto FOR EACH ROW
BEGIN

if (NEW.quantidade <> OLD.quantidade)
THEN

/*  insert modulos (descricao) values ('Teste');  Aqui você faz o que quiser, coloquei uma tabela qualquer só para mostrar */


END IF;
END $$;
DELIMITER ;
  • Is this syntax not for sql server? I tried to run but I had no answer neither from Workbench nor from command line client...

  • @Ayrtonpereira no, this is from Mysql Even. I went around here and it worked, see if there were any details missing, (delimiter maybe or END $$

Browser other questions tagged

You are not signed in. Login or sign up in order to post.