How to create id with AUTO_INCREMENT on Oracle?

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

    This is how I did this on an existing table and column (named id):

    UPDATE table SET id=ROWNUM;
    DECLARE
      maxval NUMBER;
    BEGIN
      SELECT MAX(id) INTO maxval FROM table;
      EXECUTE IMMEDIATE 'DROP SEQUENCE table_seq';
      EXECUTE IMMEDIATE 'CREATE SEQUENCE table_seq START WITH '|| TO_CHAR(TO_NUMBER(maxval)+1) ||' INCREMENT BY 1 NOMAXVALUE';
    END;
    CREATE TRIGGER table_trigger
      BEFORE INSERT ON table
      FOR EACH ROW
    BEGIN
      :new.id := table_seq.NEXTVAL;
    END;
    

提交回复
热议问题