mysql Trigger for logging, find changed columns

后端 未结 2 1729
庸人自扰
庸人自扰 2020-12-31 19:51

I am writing a trigger to keep track of all the changes that happens in a table. Unfortunately the table has 150+ columns and I wanted to avoid writing each column in the c

相关标签:
2条回答
  • 2020-12-31 20:39

    I've been doing a bit of research on this this morning and looks like I have come across much of the same search results as you. Ultimately it looks to me like there's no way to loop over all table columns and reference the corresponding old/new values. I'm settling on explicitly checking each column and then logging:

    IF (NEW.fld1 <> OLD.fld1) OR (NEW.fld1 IS NOT NULL AND OLD.fld1 IS NULL) OR (NEW.fld1 IS NULL AND OLD.fld1 IS NOT NULL) THEN
     INSERT INTO `fld_audit` (`table`, `fldname`, `oldval`, `newval`)
     VALUES ("tblname", "fld1", OLD.fld1, NEW.fld1); 
    END IF; 
    
    IF (NEW.fld2 <> OLD.fld2) OR (NEW.fld2 IS NOT NULL AND OLD.fld2 IS NULL) OR (NEW.fld2 IS NULL AND OLD.fld2 IS NOT NULL) THEN
     INSERT INTO `fld_audit` (`table`, `fldname`, `oldval`, `newval`)
     VALUES ("tblname", "fld2", OLD.fld2, NEW.fld2); 
    END IF; ...
    

    I found an inkling of another solution here. In theory you could have 3 delimited lists, one for column names, one for old vals and one for new vals. You would have to explicitly reference the old and new vals, but that would be one line (easier to maintain or copy/paste to implement on other tables) and you could then loop. So in pseudo code it would look something like this:

    fields_array = concat_ws(",", "fld1", "fld2");
    old_vals_array = concat_ws(",", OLD.fld1, OLD.fld2);
    new_vals_array = concat_ws(",", NEW.fld1, NEW.fld2);
    
    foreach fields_array as key => field_name
         INSERT INTO `fld_audit` (`table`, `fldname`, `oldval`, `newval`)
         VALUES ("tblname", field_name, old_vals_array[key], vew_vals_array[key]);
    

    I haven't thought this through too much. You might need to call into a stored procedure rather than set variables. But it might be worth looking into. I've spent enough time on my triggers already. Not sure I could validate (to my boss) trial and error time on a more elegant solution.

    0 讨论(0)
  • 2020-12-31 20:40

    As ingratiatednerd already suggested, you can use CONCAT_WS to make strings out of all required values and make a single compare statement.

    Perhaps the following is useful to someone:

    DECLARE old_concat, new_concat text;
    SET old_concat = CONCAT_WS(',', OLD.fld1, OLD.fld2, ...);
    SET new_concat = CONCAT_WS(',', NEW.fld1, NEW.fld2, ...); 
    
    IF old_concat <> new_concat
    THEN
       INSERT STATEMENT
    END IF;
    
    0 讨论(0)
提交回复
热议问题