Auto-increment in Oracle without using a trigger

后端 未结 9 1968
野的像风
野的像风 2020-11-28 09:52

What are the other ways of achieving auto-increment in oracle other than use of triggers?

9条回答
  •  粉色の甜心
    2020-11-28 10:38

    A trigger to obtain the next value from a sequence is the most common way to achieve an equivalent to AUTOINCREMENT:

    create trigger mytable_trg
    before insert on mytable
    for each row
    when (new.id is null)
    begin
        select myseq.nextval into :new.id from dual;
    end;
    

    You don't need the trigger if you control the inserts - just use the sequence in the insert statement:

    insert into mytable (id, data) values (myseq.nextval, 'x');
    

    This could be hidden inside an API package, so that the caller doesn't need to reference the sequence:

    mytable_pkg.insert_row (p_data => 'x');
    

    But using the trigger is more "transparent".

提交回复
热议问题