Oracle 的自动增量

2021-12-05 00:00:00 oracle11g 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.

推荐答案

创建表和序列

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.

现在,当你插入数据时,你不需要指定EMP_ID列——它会被触发器自动填充

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

相关文章