MySQL: Try to Port a Trigger from SQL Server
Question
Here, there's a sample of a trigger with "INSTEAD OF UPDATE" clause:
CREATE TRIGGER [dbo].[Test_PTA_Table_Update_trg]
-- ALTER TRIGGER [dbo].[Test_PTA_Table_Update_trg]
ON [dbo].[Test_PTA_Table]
INSTEAD OF UPDATE
AS
SET NOCOUNT ON
DECLARE @key int
SET @key = (SELECT TestTablePK FROM Inserted)
UPDATE Test_PTA_Table
SET DateEnd = GetDate(), DateReplaced = GetDate()
WHERE TestTablePK = @key
INSERT INTO dbo.Test_PTA_Table
(TestTableText, DateCreated, DateEffective, OperatorCode, DateReplaced)
(SELECT TestTableText, GetDate(), GetDate(), OperatorCode, NULL
FROM Inserted)
I'm trying to port the principle to MySQL:
DELIMITER ;;
DROP TRIGGER IF EXISTS attribut_trigger_update_before;
CREATE TRIGGER attribut_trigger_update_before
BEFORE UPDATE ON attribut
FOR EACH ROW BEGIN
INSERT INTO attribut SET
id_origine = OLD.id_origine,
date_v_creation = OLD.date_v_creation,
date_v_debut = OLD.date_v_debut,
date_v_fin = OLD(),
importance = OLD.importance,
description = OLD.description,
valeur = OLD.valeur,
abbreviation = OLD.abbreviation;
END;;
DELIMITER ;;
But it doesn't work.
mysql> update produit set importance=3;
ERROR 1442 (HY000): Can't update table 'produit' in stored function/trigger because it is already used by statement which invoked this stored function/trigger.
mysql>
Any idea how to do this?
Solution
This has been discussed before by others
- Making a column immutable in MySQL
- What are some good methods of structuring a MySQL audit trail to be both immutable, and perform well for usage?
Your question is a little different in this instance. You may have to experiment with INSERT IGNORE
or REPLACE
for the desired effect.
You may need to also experiment with disabling the trigger midstream : Disable trigger for just one table
Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange