我需要创建一个序列和一个触发器来自动增加表上的主键,但我不知道该怎么做.
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 的自动增量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!