Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
657 views
in Technique[技术] by (71.8m points)

oracle11g - Auto Increment for Oracle

I need to create a sequence and a trigger to auto-increment the primary key on a table but I have no idea on how to do it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Create the table and the sequence

SQL> create table staff (
  2    emp_id number primary key,
  3    staff_name varchar2(100)
  4  );

Table created.

SQL> create sequence emp_id_seq;

Sequence created.

Now, you can create a trigger that uses the sequence to populate the primary key

SQL> create trigger trg_emp_id
  2    before insert on staff
  3    for each row
  4  begin
  5    select emp_id_seq.nextval
  6      into :new.emp_id
  7      from dual;
  8  end;
  9  /

Trigger created.

Now, when you insert data, you woon't need to specify the EMP_ID column-- it will automatically be populated by the trigger

SQL> insert into staff( staff_name ) values ('Justin');

1 row created.

SQL> select * from staff;

    EMP_ID STAFF_NAME
---------- --------------------
         1 Justin

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...