Oracle: excluding updates of one column for firing a trigger

前端 未结 4 421
执念已碎
执念已碎 2021-01-04 14:20

In oracle I can specify the columns, which should induce a firing of a trigger:

create or replace trigger my_trigger
before update of col1, col2, col3 on my_         


        
相关标签:
4条回答
  • 2021-01-04 14:41

    I had the same problem yesterday. I wanted to code a trigger that fired on every field except one, the table had 103 colums.

    First I coded:

    if (:OLD.col1<>:NEW.col1 or :OLD.col2<>:NEW.col2 or :OLD.col3<>:NEW.col3 ....)
    

    But I had some problems with null values, so I added:

    if (NVL(:OLD.col1,0)<>NVL(:NEW.col1,0) or NVL(:OLD.col2,0)<>NVL(:NEW.col2,0)  ....)
    

    But then I had some problems with DATE columns, it became a mess..

    I think that the best solution is to list all columns that you want to verify in the "OF":

    AFTER INSERT OR UPDATE of cOL1, col2, col3 ... colN ON table1
    

    It was not "elegant" but... it worked perfect.

    0 讨论(0)
  • 2021-01-04 14:42

    You could do something like this:

    create or replace trigger my_trigger
    before update on my_table
    for each row
    declare
       n_cols integer := 0;
    begin
       for r in (select column_name from all_tab_columns
                 where table_name = 'MY_TABLE'
                 and owner = 'MY_SCHEMA')
       loop
          if updating(r.column_name) then
             n_cols := n_cols + 1;
             exit when n_cols > 1;
          end if;
       end loop;
       if n_cols > 1 then
          do_something;
       end if;
    end;
    

    Probably not terribly efficient though!

    0 讨论(0)
  • 2021-01-04 14:46

    I don't think there's a way you can avoid having to list all of the other columns in the table, either in the trigger body or else in the before update of ... clause.

    However, you might be able to write an alter trigger on the table to regenerate the update trigger automatically if any columns are added or removed. It's a little more work, but then the maintenance should be automatic.

    0 讨论(0)
  • 2021-01-04 14:50

    It's probably not the answer you want to hear, but I think you are rather over-exaggerating the burden of maintenance. It is not normal for a table's structure to change very often after it goes into production. If you do have a table which is subject to frequent changes of column number or name, then I would suggest you have a bigger, architectural problem.

    So, just type out all the column names now, and wait to see whether maintanance becomes an issue. It is certainly not worth coding a complicated implementation in a trigger - a tax which you will pay on every single update - in order to avoid an occasional changes to the DDL script.

    0 讨论(0)
提交回复
热议问题