oracle中的主键自动增长

2008-3-28 20:16:10 已被阅读: 发表评论

学oracle不久,在建表时发现这样一个问题,比如我现在创建一个表:student

create table STUDENT
(
ID NUMBER not null,
NAME VARCHAR2(20) default '男',
SEX VARCHAR2(4),
ADDRESS VARCHAR2(40),
MEMO VARCHAR2(60)
)

现在我想实现每插入一条数据,就让id自动增长1.在SQLSERVER中这个很好实现,但在oracle中我搞了半天,查了下资料发现要用到“序列(sequence)”,“触发器”的知识。

首先,创建一个序列:

create sequence STU
minvalue 1
maxvalue 999999999999
start with 21
increment by 1
cache 20;

然后,给表student创建一个触发器:

create or replace trigger stu_tr
before insert on student
for each row
declare
-- local variables here
begin
select stu.nextval into :new.id from dual;
end stu_tr;

来源:http://blog.csdn.net/xiaoranchenxi