Oracle中主键自增长

  最近在学习Oracle和MySql,MySql有自动配置主键自增长auto_increment,这样在输入数据的时候可以不考虑主键的添加,方便对数据库的操作。

  在Oracle中设置自增长首先用到sequence序列;

以创建学生表为例:

create table Student(id number(4) primary key,--主键id,实现自增
name varchar2(20),--名字
age number(3)--学生年龄
);

----------创建学生表-----------------

create sequence stu_sequence
increment by 1
start with 1
maxvalue 9999
minvalue 1
nocycle
cache 50;

-----------创建序列-----------------

create or replace trigger stu_auto_addid
before insert on Student
for each row
when(new.id is null)
begin
select stu_sequence.nextval into :new.id from dual;
end;
/

-----------创建触发器-----------------

接下来验证:

insert into Student(name,age) values('张三',12);

select * from Student;

结果:

51 张三 12

注:51原因是在这之前我已经试过一次,关闭数据库以后序列的缓存释放,从50开始算起。

这个序列同样可以用于其他的表。只需修改触发器中的表名。

 

 

  

posted @ 2018-04-16 20:58  Soaplay  阅读(160)  评论(0)    收藏  举报