tags:

views:

293

answers:

2

Hi i would like to achieve something like

CREATE TABLE RollingStock
( 
      Id NUMBER IDENTITY(1,1),
      Name Varchar2(80) NOT NULL      
);

in Oracle

how do i do it ?

Thanks in advance

+3  A: 

As Orbman says, the standard way to do it is with a sequence. What most people also do is couple this with an insert trigger. So when a row is inserted without an ID, the trigger files to fill out the ID for you from the sequence.

CREATE SEQUENCE SEQ_ROLLINGSTOCK_ID START WITH 1 INCREMENT BY 1 NOCYCLE;

CREATE OR REPLACE TRIGGER BI_ROLLINGSTOCK
BEFORE INSERT ON ROLLINGSTOCK
REFERENCING OLD AS OLD NEW AS NEW
FOR EACH ROW
 WHEN (NEW.ID IS NULL)
BEGIN
  select SEQ_ROLLINGSTOCK_ID.NEXTVAL
   INTO :NEW.ID from dual;
END;

This is one of the few cases where it makes sense to use a trigger in oracle.

Matthew Watson
Note that the trigger is not entirely necessary. So long as whenever an insert is performed the value from the sequence is used you are fine. It isn't Automatic, but it doesn't require much discipline either. I try desperately to avoid triggers as a matter of personal taste.
Adam Hawkes
@Adam, I totally agree. This is one of the few places which I will use a trigger, mainly due to the horrendous lack of naming standards in the database I look after, making it near impossible to know the correct sequence to use.
Matthew Watson
A: 

If you really don't care what the primary key holds, you can use a RAW type for the primary key column which holds a system-generated guid in binary form.

CREATE TABLE RollingStock 
(  
  ID RAW(16) DEFAULT SYS_GUID() PRIMARY KEY, 
  NAME VARCHAR2(80 CHAR) NOT NULL       
); 
Adam Hawkes