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;

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

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

相关文章:

  • 2021-11-27
  • 2022-12-23
  • 2022-01-19
  • 2022-12-23
  • 2022-01-12
  • 2021-06-27
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-10-19
  • 2022-12-23
  • 2021-12-04
  • 2022-02-10
  • 2021-05-08
  • 2021-10-12
  • 2022-01-14
相关资源
相似解决方案