Oracle
 sql >> Database >  >> RDS >> Oracle

Attivazione di Oracle che controlla il vincolo su base mensile

l'uso di un trigger, sebbene sembri funzionare, è un modo pericoloso per farlo, poiché le sessioni in esecuzione in parallelo non vedranno i dati inseriti dalla sessione in corso. Puoi farlo tramite una vista materializzata:

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