oracle如何创建表的自增ID(通过触发器)

Oracle中创建表的自增ID(通过触发器),序列的自增ID和触发器的自增ID的区别

1、新增数据(序列)

--创建示例表 --
create table Student(
    stuId number(9) not null,
    stuName varchar2(20) not null,
    stuMsg varchar2(50) null
)

 -- 创建序列  Student_StuId_Seq --
 create sequence Student_StuId_Seq
 increment by 1
 start with 1
 minvalue 1
 maxvalue 999999999;
 
 --调用序列 --
 select Student_StuId_Seq.Nextval 序列号 from dual;
 
 --插入数据(序列)--
 insert into Student(STUID,STUNAME) values(Student_StuId_Seq.Nextval,'王五');

2、新增数据(触发器)

--创建示例表 --
create table Student(
    stuId number(9) not null,
    stuName varchar2(20) not null,
    stuMsg varchar2(50) null
)

 -- 创建序列  Student_StuId_Seq --
 create sequence Student_StuId_Seq
 increment by 1
 start with 1
 minvalue 1
 maxvalue 999999999;
 
--创建触发器 --
create or replace trigger Student_StuId_Trigger
before insert on Student  ----(sysrole为表名)
for each row----触发每一行
begin
select Student_StuId_Seq.Nextval into :new.StuId from dual;
end;

--新增数据(触发器)--
insert into Student(STUNAME) values('赵六');

3、查询结果

--查询数据--
select * from Student;

PS: 序列可以理解成一个获取表的自增ID的函数(手动),触发器是当新增数据(自动)时,获取表的自增ID

posted @ 2018-05-08 16:18  小小邪  阅读(1155)  评论(0编辑  收藏  举报