user1940791
user1940791

Reputation: 13

trigger insert and update oracle error

Friend, I have question about cascade trigger. I have 2 tables, table data that has 3 attributes (id_data, sum, and id_tool), and table tool that has 3 attributes (id_tool, name, sum_total). table data and tool are joined using id_tool.

I want create trigger for update info sum_total. So , if I inserting on table data, sum_total on table tool where tool.id_tool = data.id_tool will updating too.

I create this trigger, but error ora-04090.

create or replace trigger aft_ins_tool
after insert on data
for each row
declare
v_stok number;
v_jum number;
begin
    select sum into v_jum
    from data
    where id_data= :new.id_data;

    select sum_total into v_stok
    from tool
    where id_tool= 
    (select id_tool
        from data
        where id_data= :new.id_data);

    if inserting then
    v_stok := v_stok + v_jum;
    update tool
    set sum_total=v_stok
    where id_tool=
    (select id_tool
        from data
        where id_data= :new.id_data);
    end if;
end;

/

please give me opinion. Thanks.

Upvotes: 0

Views: 234

Answers (1)

APC
APC

Reputation: 146349

The ora-04090 indicates that you already have an AFTER INSERT ... FOR EACH ROW trigger on that table. Oracle doesn't like that, because the order in which the triggers fire is unpredictable, which may lead to unpredictable results, and Oracle really doesn't like those.

So, your first step is to merge the two sets of code into a single trigger. Then the real fun begins.

Presumably there is only one row in data matching the current value of id_data (if not your data model is rally messed up and there's no hope for your situation). Anyway, that means the current row already gives you access to the values of :new.sum and :new.id_tool. So you don't need those queries on the data table: removing those selects will remove the possibility of "mutating table" errors.

As a general observation, maintaining aggregate or summary tables like this is generally a bad idea. Usually it is better just to query the information when it is needed. If you really have huge volumes of data then you should use a materialized view to maintain the summary, rather than hand-rolling something.

Upvotes: 1

Related Questions