Oracle
 sql >> Base de données >  >> RDS >> Oracle

Déclencheur Oracle qui vérifie la contrainte sur une base mensuelle

l'utilisation d'un déclencheur, bien qu'il semble fonctionner, est une façon dangereuse de le faire, car les sessions exécutées en parallèle ne verront pas les données insérées de la session en cours. vous pouvez le faire via une vue matérialisée :

SQL> create table rent (id number primary key, member varchar2(30), book varchar2(20), date_rented date);

Table created.

SQL> create index rent_ix1 on rent ( member, date_rented);

Index created.

SQL> create materialized view log on rent with rowid(member,date_rented)
  2  including new values;

Materialized view log created.

SQL> create materialized view rent_month_check
  2  refresh fast on commit
  3  as
  4  select trunc(date_rented, 'mm') month, member, count(*) rentals
  5    from rent
  6   group by trunc(date_rented, 'mm'), member;

Materialized view created.

SQL> alter table rent_month_check
  2  add constraint rent_month_check_ck1 check (rentals <= 4);

Table altered.

SQL> insert into rent values(1, 'DazzaL', 'crime', sysdate);

1 row created.

SQL> commit;

Commit complete.

SQL> insert into rent values(2, 'DazzaL', 'mystery', sysdate+1);

1 row created.

SQL> commit;

Commit complete.

SQL> insert into rent values(3, 'DazzaL', 'fantasy', sysdate+2);

1 row created.

SQL> commit;

Commit complete.

SQL> insert into rent values(4, 'DazzaL', 'politics', sysdate+3);

1 row created.

SQL> commit;

Commit complete.

SQL> insert into rent values(5, 'DazzaL', 'thriller', sysdate+4);

1 row created.

SQL> commit;
commit
*
ERROR at line 1:
ORA-12008: error in materialized view refresh path
ORA-02290: check constraint (TEST.RENT_MONTH_CHECK_CK1) violated


SQL> select * from rent_month_check;

MONTH     MEMBER                            RENTALS
--------- ------------------------------ ----------
01-NOV-12 DazzaL                                  4