I have a Translation table and I want every update to it to automatically be logged in a TranslationHistory table.
I created this trigger for that purpose.
CREATE TRIGGER TranslationUpdate AFTER UPDATE ON Translation FOR EACH ROW BEGIN
DECLARE N DATETIME;
DECLARE ActionString VARCHAR(1000);
SET N = now();
SET ActionString = '';
IF NEW.TranslatorID <> OLD.TranslatorID THEN
SET ActionString = CONCAT(ActionString, 'TranslatorID(', OLD.TranslatorID, ' -> ', NEW.TranslatorID, ') ');
END IF;
IF NEW.StartDate <> OLD.StartDate THEN
SET ActionString = CONCAT(ActionString, 'StartDate(', OLD.StartDate, ' -> ', NEW.StartDate, ') ');
END IF;
IF NEW.DueDate <> OLD.DueDate THEN
SET ActionString = CONCAT(ActionString, 'DueDate(', OLD.DueDate, ' -> ', NEW.DueDate, ') ');
END IF;
IF NEW.EndDate <> OLD.EndDate THEN
SET ActionString = CONCAT(ActionString, 'EndDate(', OLD.EndDate, ' -> ', NEW.EndDate, ') ');
END IF;
IF NEW.Notes <> OLD.Notes THEN
SET ActionString = CONCAT(ActionString, 'Notes(', OLD.Notes, ' -> ', NEW.Notes, ') ');
END IF;
INSERT INTO TranslationHistory (TranslationID, Date, Action)
VALUES (NEW.ID, N, ActionString);
END;
I don’t like it very much because it’s so long, tedious, and repetitious and I’m sure it’s not good SQL. I’d like a DRYer way to do this. Is there a way to do this without having to manually specify details for each column?
You could wrap each of the code bocks up into a function, but it wouldn’t be much less code in your main procedure than refactoring:
into this: