Skip to Main Content
  • Questions
  • Manually refresh materialized view in trigger

Breadcrumb

Question and Answer

Chris Saxon

Thanks for the question, Christophe.

Asked: November 12, 2018 - 4:24 pm UTC

Last updated: November 13, 2018 - 4:22 pm UTC

Version: 11.2.0.1.0

Viewed 1000+ times

You Asked

Hello,

I have a set of MV that are dependant each other and from master tables.
All are elligible to be fast-refreshed but for a reason I don't know, in some tables after a delete or update the fast refresh is longer than the complete one.

So I have to set-up a manual refresh, such as (for insert/delete) a complete on MV1 and a fast to the related MV.

The problem is that refreshing a MV produces a commit, which is not allowed in triggers.
(I tried with compound triggers)

Is there any solution ?

and Chris said...

You can declare the trigger as using an autonomous transaction...

...but this won't give you what you're looking for!

This is a new transaction. So the trigger can't see the changed rows from the calling statement:

create table t (
  c1 int primary key
);

create materialized view log on t 
  with rowid including new values;

create materialized view mv 
refresh fast on demand 
as 
  select count(*) from t;
  
create or replace trigger t_aiuder
after insert or update or delete on t
declare
  pragma autonomous_transaction;
begin
  if inserting then
    dbms_mview.refresh ( 'mv', 'F' );
  else
    dbms_mview.refresh ( 'mv', 'C' );
  end if;
  commit;
end;
/

insert into t values ( 1 );

select count(*) from t;

COUNT(*)   
         1 

select * from mv;

COUNT(*)   
         0 

commit;

delete t;

select count(*) from t;

COUNT(*)   
         0 

select * from mv;

COUNT(*)   
         1 

commit;


Submitting an old-style job in the trigger may help. Or you can manually write the refresh after your transactions.

Rating

  (1 rating)

Is this answer out of date? If it is, please let us know via a Comment

Comments

Mina Sifeen, March 13, 2019 - 10:09 am UTC


More to Explore

Design

New to good database design? Check out Chris Saxon's full fundamentals class.