How to create id with AUTO_INCREMENT on Oracle?

后端 未结 16 1638
死守一世寂寞
死守一世寂寞 2020-11-21 04:52

It appears that there is no concept of AUTO_INCREMENT in Oracle, up until and including version 11g.

How can I create a column that behaves like auto increment in Or

16条回答
  •  死守一世寂寞
    2020-11-21 05:56

    SYS_GUID returns a GUID-- a globally unique ID. A SYS_GUID is a RAW(16). It does not generate an incrementing numeric value.

    If you want to create an incrementing numeric key, you'll want to create a sequence.

    CREATE SEQUENCE name_of_sequence
      START WITH 1
      INCREMENT BY 1
      CACHE 100;
    

    You would then either use that sequence in your INSERT statement

    INSERT INTO name_of_table( primary_key_column, <> )
      VALUES( name_of_sequence.nextval, <> );
    

    Or you can define a trigger that automatically populates the primary key value using the sequence

    CREATE OR REPLACE TRIGGER trigger_name
      BEFORE INSERT ON table_name
      FOR EACH ROW
    BEGIN
      SELECT name_of_sequence.nextval
        INTO :new.primary_key_column
        FROM dual;
    END;
    

    If you are using Oracle 11.1 or later, you can simplify the trigger a bit

    CREATE OR REPLACE TRIGGER trigger_name
      BEFORE INSERT ON table_name
      FOR EACH ROW
    BEGIN
      :new.primary_key_column := name_of_sequence.nextval;
    END;
    

    If you really want to use SYS_GUID

    CREATE TABLE table_name (
      primary_key_column raw(16) default sys_guid() primary key,
      <>
    )
    

提交回复
热议问题