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

前端 未结 2 1341
孤街浪徒
孤街浪徒 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:45

    If your MAX(noteid) is 799, then try:

    CREATE SEQUENCE noteseq
        START WITH 800
        INCREMENT BY 1
    

    Then when inserting a new record, for the NOTEID column, you would do:

    noteseq.nextval
    
    0 讨论(0)
  • 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;
    
    0 讨论(0)
提交回复
热议问题