How to create id with AUTO_INCREMENT on Oracle?

后端 未结 16 1634
死守一世寂寞
死守一世寂寞 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:33

    Here are three flavors:

    1. numeric. Simple increasing numeric value, e.g. 1,2,3,....
    2. GUID. globally univeral identifier, as a RAW datatype.
    3. GUID (string). Same as above, but as a string which might be easier to handle in some languages.

    x is the identity column. Substitute FOO with your table name in each of the examples.

    -- numerical identity, e.g. 1,2,3...
    create table FOO (
        x number primary key
    );
    create sequence  FOO_seq;
    
    create or replace trigger FOO_trg
    before insert on FOO
    for each row
    begin
      select FOO_seq.nextval into :new.x from dual;
    end;
    /
    
    -- GUID identity, e.g. 7CFF0C304187716EE040488AA1F9749A
    -- use the commented out lines if you prefer RAW over VARCHAR2.
    create table FOO (
        x varchar(32) primary key        -- string version
        -- x raw(32) primary key         -- raw version
    );
    
    create or replace trigger FOO_trg
    before insert on FOO
    for each row
    begin
      select cast(sys_guid() as varchar2(32)) into :new.x from dual;  -- string version
      -- select sys_guid() into :new.x from dual;                     -- raw version
    end;
    /
    

    update:

    Oracle 12c introduces these two variants that don't depend on triggers:

    create table mytable(id number default mysequence.nextval);
    create table mytable(id number generated as identity);
    

    The first one uses a sequence in the traditional way; the second manages the value internally.

提交回复
热议问题