如果达到序列 MAX_VALUE 则更新 ID

Update ID if Sequence MAX_VALUE reached

我正在使用以下触发器插入我的测试 Table:

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。我可以在触发器中执行此操作吗?

如果我理解得很好,你可能需要一个INSTEAD OF触发器;要构建这样的触发器,您需要在 table 上创建一个 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>