我有一个翻译表,我希望每次更新都能自动记录在TranslationHistory表中。
我为此目的创建了这个触发器。
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;
我不太喜欢它,因为它太长,乏味和重复,我确信它不是很好的SQL。我想要一个DRYer的方法来做到这一点。有没有办法在不必手动指定每列的详细信息的情况下执行此操作?
答案 0 :(得分:0)
你可以把每个代码块都包装成一个函数,但是主程序中的代码不会比重构更少:
IF NEW.TranslatorID <> OLD.TranslatorID THEN
SET ActionString = CONCAT(ActionString, 'TranslatorID(', OLD.TranslatorID, ' -> ', NEW.TranslatorID, ') ');
END IF;
进入这个:
SET ActionString = if(NEW.TranslatorID = OLD.TranslatorID, ActionString, CONCAT(ActionString, 'TranslatorID(', OLD.TranslatorID, ' -> ', NEW.TranslatorID, ') '));