本文主要是介绍Oracle实现自增字段的两种方法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一,创建student表
--创建student表
create table student( id number not null, --学生id name varchar2(10) not null --学生姓名
);
二,实现学生id的自增 (需先创建序列)
create sequence student_id_seq; --创建序列
1.使用序列的.NEXTVAL方法向表插入字段值
insert into student values (student_id_seq.nextval,'张三');
insert into student values (student_id_seq.nextval,'李四');
select * from student; --查询表
使用Oralcle11g查询表的时候,会发现自增的字段初始值不为1,因为从Oracle 11g开始,有一种新特性叫“延迟分配段空间”,详情请参考 Oracle 11g 新特性 ,可通过修改序列的默认起始值来达到所需自增值。
2.使用触发器创建自增字段
a.创建触发器
create or replace trigger test_idbefore insert on student --before:执行DML等操作之前触发
for each row --行级触发器
begin select student_id_seq.nextval into :new.id from dual;
end;
/
触发时机:
before:能够防止某些错误操作发生而便于回滚或实现某些业务规则,适用于实现自增字段;
after:在DML等操作发生之后发生,这种方式便于记录该操作或做某些事后处理信息;
instead of:触发器为替代触发器。
b.数据添加
insert into student(name) values ('张三');
insert into student (name) values ('李四');
select * from student;
---------------------
作者:北风丶
来源:CSDN
原文:https://blog.csdn.net/qq_40774525/article/details/80160403
版权声明:本文为博主原创文章,转载请附上博文链接!
这篇关于Oracle实现自增字段的两种方法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!