开发者

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

I have a table with the following column:

NOTEID      NUMBER NOT NULL,

For all intents and purposes, this column is the primary key. This table has a few thousand rows, each with a unique ID. Before, the application would SELECT the MAX() value from the table, add one, then use that as the next value. This is a horrible solution, and is not transaction or thread safe (in fact, before they didn't even have a UNIQUE constraint on the column and I could see the same NOTEID was duplicated in 9 different occasions)..

I'm rather new to Oracle, so I'd like to know the best syntax to ALTER this table and make this column auto-increment instead. If possible, I'd开发者_如何学C like to make the next value in the sequence be the MAX(NOTEID) + 1 in the table, or just make it 800 or something to start out. Thanks!


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;


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜