How to create id with AUTO_INCREMENT on Oracle?

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

    In Oracle 12c onward you could do something like,

    CREATE TABLE MAPS
    (
      MAP_ID INTEGER GENERATED ALWAYS AS IDENTITY (START WITH 1 INCREMENT BY 1) NOT NULL,
      MAP_NAME VARCHAR(24) NOT NULL,
      UNIQUE (MAP_ID, MAP_NAME)
    );
    

    And in Oracle (Pre 12c).

    -- create table
    CREATE TABLE MAPS
    (
      MAP_ID INTEGER NOT NULL ,
      MAP_NAME VARCHAR(24) NOT NULL,
      UNIQUE (MAP_ID, MAP_NAME)
    );
    
    -- create sequence
    CREATE SEQUENCE MAPS_SEQ;
    
    -- create tigger using the sequence
    CREATE OR REPLACE TRIGGER MAPS_TRG 
    BEFORE INSERT ON MAPS 
    FOR EACH ROW
    WHEN (new.MAP_ID IS NULL)
    BEGIN
      SELECT MAPS_SEQ.NEXTVAL
      INTO   :new.MAP_ID
      FROM   dual;
    END;
    /
    

提交回复
热议问题