Behaviour of insertion trigger when defining autoincrement in Oracle

Posted by Genba on Stack Overflow See other posts from Stack Overflow or by Genba
Published on 2010-06-07T12:26:43Z Indexed on 2010/06/07 12:32 UTC
Read the original article Hit count: 521

Filed under:
|
|
|
|

I have been looking for a way to define an autoincrement data type in Oracle and have found these questions on Stack Overflow:

  1. Autoincrement in Oracle
  2. Autoincrement Primary key in Oracle database

The way to use autoincrement types consists in defining a sequence and a trigger to make insertion transparent, where the insertion trigger looks so:

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;

I have some doubts about the behaviour of this trigger:

  1. What does this trigger do when the supplied value of "id" is different from NULL?
  2. What does the colon before "new" mean?

I want the trigger to insert the new row with the next value of the sequence as ID whatever the supplied value of "new.id" is. I imagine that the WHEN statement makes the trigger to only insert the new row if the supplied ID is NULL (and it will not insert, or will fail, otherwise).

Could I just remove the WHEN statement in order for the trigger to always insert using the next value of the sequence?

© Stack Overflow or respective owner

Related posts about sql

Related posts about Oracle