How to use oracle check constraints to limit number of registration?

后端 未结 3 1112
礼貌的吻别
礼貌的吻别 2021-01-28 14:57

I\'ve a user table with unique user_id. User can register using there id. Now I want to limit the max. registration per user using CHECK constraints. so I use this:



        
3条回答
  •  无人共我
    2021-01-28 15:37

    Under certain conditions, you can enforce table restrictsion with materialized views:

    create table tq84_t (
      user_id   number,
      foo       varchar2(10),
      constraint pk_tq84_t primary key (user_id, foo)
    );
    
    create materialized view log on tq84_t;
    
    create materialized view tq84_mv 
     refresh on commit
    as
      select user_id, count(*) cnt
        from tq84_t
       group by user_id;
    
    alter table tq84_mv
      add constraint check_max_2_registrations 
      check (cnt < 3);
    

    With this materialized view, Oracle checks the constraint on the materialized view when you commit:

    insert into tq84_t values (1, 'a');
    insert into tq84_t values (1, 'b');
    
    commit;
    

    This works. The following doesn't:

    insert into tq84_t values (1, 'c');
    
    commit;
    

    It fails with

    ORA-12008: error in materialized view refresh path
    ORA-02290: check constraint (META.CHECK_MAX_2_REGISTRATIONS) violated
    

提交回复
热议问题