Oracle - Modify an existing table to auto-increment a column

前端 未结 2 1368
孤街浪徒
孤街浪徒 2021-01-13 11:56

I have a table with the following column:

NOTEID      NUMBER NOT NULL,

For all intents and purposes, this column is the primary key. This

2条回答
  •  青春惊慌失措
    2021-01-13 12:56

    You can't alter the table. Oracle doesn't support declarative auto-incrementing columns. You can create a sequence

    CREATE SEQUENCE note_seq
      START WITH 800
      INCREMENT BY 1
      CACHE 100;
    

    Then, you can create a trigger

    CREATE OR REPLACE TRIGGER populate_note_id
      BEFORE INSERT ON note
      FOR EACH ROW
    BEGIN
      :new.note_id := note_seq.nextval;
    END;
    

    or, if you want to allow callers to specify a non-default NOTE_ID

    CREATE OR REPLACE TRIGGER populate_note_id
      BEFORE INSERT ON note
      FOR EACH ROW
    BEGIN
      IF( :new.note_id is null )
      THEN 
        :new.note_id := note_seq.nextval;
      END IF;
    END;
    

提交回复
热议问题