Oracle trigger that check constraint on a monthly basis

前端 未结 2 893
灰色年华
灰色年华 2021-01-23 14:20

just wonder is it possible to create a trigger to check on a specify constraint base on monthly basis.

eg.
table rent
|ID|Member|book|
-------------

2条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-23 14:51

    If the table stores only actual data then it is quite simple:

    create or replace trigger tr_rent
    before insert on rent
    for each row 
    declare
      v_count number;
    begin
      select count(*) into v_count
      from rent where member = :new.member;
    
      if v_count >= 4 then
        raise_application_error(-20001, 'Limit reached');
      end if;
    end;
    /
    

    But if the table store historical data as well then you need some timestamp column, f.e. rent_date. So the count-query should be changed to the following:

    select count(*) into v_count
    from rent where member = :new.member
    and rent_date > add_months(sysdate, -1);
    

    In some cases reading a table that is currently being modified may lead to "mutating table error", but the trigger above is safe.

提交回复
热议问题