Oracle does not have an autonumber like SQLServer has. Oracle's way to for autonumbers is using sequences and triggers. The sequence makes sure that unique numbers are generated while the trigger fills the these numbers into the column for which an autonumber is desired. This is demonstrated in the following. I need a table with a autonumber column. In this case, it will be column id . create table tbl_autonumber( Then, the sequence: create sequence seq_autonumber; And the trigger. It fires whenever a new record is inserted and assigns the sequence's next value (using nextval) to :new.id. create trigger trg_autonumber Now, three records are inserted: insert into tbl_autonumber (txt) values('bar'); select * from tbl_autonumber; The trigger did its job and filled id with unique values: ID TXT Now, trying to circumvent the 'autonumber' and specify an aribtrary id: insert into tbl_autonumber (id, txt) values(100, '###'); Doesn't work, is overwritten by trigger! select * from tbl_autonumber; ID TXT Changing the trigger and ... create or replace trigger trg_autonumber .... trying again to overrule the trigger: insert into tbl_autonumber (id, txt) values(111, 'This'); And indeed, it worked. However.... select * from tbl_autonumber; ID TXT .... it should be clear that it is a bad idea to supply primary keys if there is a sequence. |
Sunday, November 19, 2006
Oracle and Autonumber
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment