sql - How to create a trigger to record changes for Insert,Update,Delete for multiple tables -


i have 2 tables in database.this can increase later on.i want add table audit track changes existing 2 tables.i want track change done of these table audit table structure
id
table_name
field_name
old_value
new_value
modified_by
date_of_modification

so want have 1 trigger both tables can fired on insert,update or delete either of tables. when trigger fired want insert values in audit.when i'm updating want old value , new value.when inserting want old value nothing , new value inserted.when deleting want old value old existing value , new value deleted.

i'm not quite sure question is. triggers can use :old , :new keywords this:

create trigger table1_trg after insert or update or delete on table1 each row begin    if :old.col1 null , :new.col1 not null    or :old.col1 not null , :new.col1 null    or :old.col1 != :new.col1           insert audit_table ...    end if;     -- ditto col2, col3, ... end; 

there no generic way this, have have code each column. however, can encapsulate logic this:

procedure log_col_change    ( p_table_name varchar2    , p_column_name varchar2    , p_old_val varchar2    , p_new_val varchar2    ) begin    if p_old_val null , p_new_val not null    or p_old_val not null , p_new_val null    or p_old_val != p_new_val           insert audit_table ...    end if; end;  -- overloaded version handles date columns without losing time component procedure log_col_change    ( p_table_name varchar2    , p_column_name varchar2    , p_old_val date    , p_new_val date    ) begin    log_col_change (p_table_name, p_column_name                   , to_char(p_old_val,'yyyy-mm-dd hh24:mi:ss')                   , to_char(p_new_val,'yyyy-mm-dd hh24:mi:ss')                   ); end; 

the trigger then:

create trigger table1_trg after insert or update or delete on table1 each row begin    log_col_change ('mytable', 'col1', :old.col1, :new.col1);    log_col_change ('mytable', 'col2', :old.col2, :new.col2);    ... etc. end; 

nb best practice put procedures package.


Comments

Popular posts from this blog

ASP.NET/SQL find the element ID and update database -

jquery - appear modal windows bottom -

c++ - Compiling static TagLib 1.6.3 libraries for Windows -