Oracle自动增量 [英] Auto Increment for Oracle

查看:89
本文介绍了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

这篇关于Oracle自动增量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆