2012-06-20 60 views
0

我有一個翻譯表,我想每次更新它都會自動記錄在TranslationHistory表中。有沒有辦法重構這個MySQL歷史觸發器?

我爲此創建了這個觸發器。

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

你可以包裝每個代碼bocks成一個功能,但它不會在你的主過程更少的代碼比重構:

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, ') ')); 
相關問題