Autonumber fields
Administration Tips
Autonumber fields in Oracle Microsoft Access allows a column in a table to be declared as an 'autonumber' field, which guarantees uniqueness for every row inserted (what I believe is termed a 'synthetic' primary key), although you can also use it in any column, even if it isn't the primary key of the table. SQL Server has something very similar, called 'increment'. The question arises: is there such a feature in Oracle? To which the reply is "no, but you can fudge it". In Oracle, you are going to need to access a Sequence, which will generate the unique numbers for you. The basic command would be: CREATE SEQUENCE SEQ_BLAH;
But that's not enough: you probably want the next sequence number to be extracted and inserted automatically whenever a new record is inserted. For that, you'll have to create a trigger on the relevant table, like this: CREATE OR REPLACE TRIGGER BLAH_AUTO BEFORE INSERT ON TABLE_NAME FOR EACH ROW BEGIN SELECT SEQ_BLAH.NEXTVAL INTO
:NEW.COLUMN_NAME
FROM DUAL;
END;
/ The trigger will fire any time you try to insert a new record into table table_name, and will grab the next number from the seq_blah sequence we created earlier. It assigns that to the relevant column as its new value (even if one is manually supplied by the User -the sequence value overrides anything a User submits). One thing to watch out for: because of the way Oracle caches sequences, it is NOT guaranteed that all autonumbers generated in this way will be in sequence without a any gaps. In other words, a subsequent select on the relevant table might reveal autogenerated numbers to be 1,2,4,6,7,11 and so on. All numbers are guaranteed unique, but you can do nothing about the potential gaps. If that's a problem for you, you'll have to think of another method (such as a separate table containing the seed number from which inserts select the next number and increment it -if the original insert fails, the update to the seed number fails. This method introduces potentially awful contention, locking and performance issues, however). Otherwise, this rough-and-ready fudge will do the trick.
Copyright Š Howard Rogers 2001
10/17/2001
Page 1 of 1