如果达到序列MAX_VALUE则更新ID

时间:2017-03-16 09:10:13

标签: oracle database-trigger

我正在使用以下TRIGGER插入我的测试表:

create or replace
TRIGGER TRG_CYCLE 
BEFORE INSERT ON TEST_CYCLE 
FOR EACH ROW
BEGIN
 IF :NEW.LOGID IS NULL
  THEN SELECT SEQ_CYCLE.nextval INTO :NEW.LOGID from dual;
 END IF;
END;

SEQ_CYCLE是序列。现在我必须使用CYCLE选项,以便在达到MAX_VALUE后从1开始。由于我不想要重复的LOGID,如果LOGID存在,我想要进行更新,如果不是INSERT。我可以在触发器内执行此操作吗?

1 个答案:

答案 0 :(得分:0)

如果我理解得很清楚,您可能需要INSTEAD OF触发器;要构建这样的触发器,您需要在表上创建一个VIEW并在此视图上构建触发器。

例如,假设你有:

create sequence SEQ_CYCLE maxValue 3 cycle nocache;
create table TEST_CYCLE ( logId number, someColumn varchar2(20));

您可以在视图上创建视图和触发器:

create or replace view v_test_cycle as select * from test_cycle;

create or replace trigger trgCycle
instead of insert on v_test_cycle
for each row 
declare
    vCheck number;
    vSeqVal number := SEQ_CYCLE.nextVal;
begin
    select count(*)
    into vCheck
    from v_test_cycle
    where logId = vSeqVal;
    --
    if vCheck = 0 then
        insert into test_cycle(logId, someColumn) values ( vSeqVal, :NEW.someColumn);
    else
        update test_cycle
        set someColumn = :NEW.someColumn
        where logId = vSeqVal;
    end if;
end;

如果你在视图上执行INSERT,这就是你得到的:

SQL> select * from test_cycle;

no rows selected

SQL> insert into v_test_cycle(someColumn) values('some value 1');

1 row created.

SQL> insert into v_test_cycle(someColumn) values('some value 2');

1 row created.

SQL> insert into v_test_cycle(someColumn) values('some value 3');

1 row created.

SQL> insert into v_test_cycle(someColumn) values('some value 4');

1 row created.

SQL> insert into v_test_cycle(someColumn) values('some value 5');

1 row created.

SQL> select * from test_cycle;

     LOGID SOMECOLUMN
---------- --------------------
         1 some value 4
         2 some value 5
         3 some value 3

SQL>