Oracle
 SQL >> Database >  >> RDS >> Oracle

Aggiungere colonna auto-increment a tabella Oracle esistente

Non puoi alterare direttamente la tabella, perché Oracle non supporta colonne auto-increment dichiarative. Crea una sequenza:

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

Poi crea un trigger:

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

Se vuoi che i chiamanti possano fornire un NOTE_ID non predefinito:

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;