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;
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAATEAAABOCAIAAADHBLafAAAJz0lEQVR4nO2dPa6DvBKGvSdLFGwlFFSsw51blnAUl9atrkT7RUJuvQHKT+nR3QC3AAzYxpBAsIF55SKHPzOTeTJm7OSgekYI/aO1uq7/QWhu1xb9/f01TbPxIqAaPLmrfDkTufYZsLVMuo/5QhBJewk8uaNCZPIwQSTtJfDkjgImIZJ2EHhyRwGTEEk7CDy5o27NJAgEUkJ1XfP//BcaNGiBtI7JBgQChaGPmSSE/O5uAulxi+q6Xn/wuUzbotu65QvDJ0yuGey2p/1sLB1Ejxu18m7//v5OZ9oW3dYtnxoOTO6v2wafW7d1CzDpX7cNPrdu65ZbMCl5GkWoVZRSTinvd/EUmYqorOta0v6clGtHtwfYzu4OHc7tTohSyuXMDW8Jvl+Y1u3tjZxcSx2vrDS3TE8deku5/Z60awTqFr5g2lK/ar+KiDSl1pC4AZM8jQZHSk6jkWMl7ffxtN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FKmG8Dv2ttCJm/EKVeKLd4p+gXTDoMD4XJf8vn8zlG0pI5T8rku2JsOkS0VmUc85Mix9iWzaz5Vm8FsT6+em+L0aXc4p2iXzDpUDBM6ojav0Z5Sia1VhFrcrMxKdqRqsj73DhpLEEYu6dJWm7RcDrLQ6m+ApPnYrIkD1XvuRiTswsALExWBCNMKjuTIsc4F0s1Hpbo5VZBsiCGu8DkiZgsycP1nWbvwbShCZLN8mNhsudN5BjnXVUGt4PVinQvGkHi2UkOkWMLsZM6cOjtekyubOEw+XQAeXImmQPIt41JVQoy8qQg8ZDrRI6RvdLDkm4+U2/zpwTXgEm/TD4fTiDPzCRLnEC+bUyqgq3GJNNGvzMPqCzD84sEBIkRik+AJTDpkUkTyJKQK8yF2IAcL8QZgs/AJmEVSzLCRkyKnJjDTlEJvdMiwe61BEWCAlvZY23ApC8mS4IfpJzoSfAl5kIEiRNSCTFqLLdkMJ1J9cRYsSRGyWfwsGR5cU+bKkMpw841YNIXk8+H+T9JbIvrTsgkS6ymLTHJJtVRwTKMEMbmWpyCsZwkWZLkagJzeZzcNuvShdAaMOm9xrOgEzL5QfANf1aMWGozQhSEZEmSYRxP2zASFiz3s1bud27xjgcwCUxCm7jFOx7AJDAJbeIW73gEweSxP3z1geA3skD3kZ4nQSCQdwGTIFBYAiZBoLAETIJAYQmYBIHCEjAJAoUlYBIECkv/BzMQaiXc7T7EAAAAAElFTkSuQmCC" alt="" />
PS: 序列可以理解成一个获取表的自增ID的函数(手动),触发器是当新增数据(自动)时,获取表的自增ID