Tuesday, June 12, 2007

How to Create Auto Increment Column in Oracle

Oracle hasn't got a Auto Increment feature by default as SQL Server.
But there are several ways to do this.
I'll mention trigger way.

  • First you define a number column in your table.
  • Then create a sequence.
  • And create a "before trigger" using sequence on table.

  1. You have a table like this:
    CREATE TABLE SERVICES
    (
    SERVICEID NUMBER(10) NOT NULL,
    SERVICENAME VARCHAR2(20 BYTE) NOT NULL
    )
  2. Create a sequence:
    create sequence SERVICES_seq
    start with 1
    increment by 1
    nomaxvalue;
  3. Create a before insert trigger:
    CREATE trigger tr_SERVICES
    before insert on SERVICES
    for each row
    begin
    select SERVICES_seq.nextval into :new.SERVICEID from dual;
    end;
    /

That's it!

No comments: