How does oracle create an auto-incrementing ID for a table (through triggers)

The difference between the auto-increment ID of the created table (through triggers), the auto-increment ID of the sequence and the auto-increment ID of the trigger in Oracle

1. New data (sequence)

--Create a sample 
table-- create  table Student(
    stuId number(9) not null,
    stuName varchar2(20) not null,
    stuMsg varchar2(50) null
)

 --create sequence Student_StuId_Seq -- 
 create sequence Student_StuId_Seq
 increment by 1
 start with 1
 minvalue 1
 maxvalue 999999999;
 
 --Call sequence-- 
 select Student_StuId_Seq.Nextval serial number from dual;
 
 --Insert data (sequence)-- 
 insert into  Student (STUID,STUNAME) values ​​(Student_StuId_Seq.Nextval, ' Wang Wu ' );

2. New data (trigger)

--Create a sample 
table-- create  table Student(
    stuId number(9) not null,
    stuName varchar2(20) not null,
    stuMsg varchar2(50) null
)

 --create sequence Student_StuId_Seq -- 
 create sequence Student_StuId_Seq
 increment by 1
 start with 1
 minvalue 1
 maxvalue 999999999;
 
--Create trigger-- create 
or replace trigger Student_StuId_Trigger   
before insert  on Student   -- --(sysrole is the table name) 
for each row -- --trigger each row 
begin 
select Student_StuId_Seq.Nextval into :new.StuId from dual;
 end ;

--Add data (trigger)-- 
insert into  Student (STUNAME) values ​​( ' Zhao Liu ' );

3. Query results

--Query 
data-- select  *  from Student;

PS: The sequence can be understood as a function (manually) to obtain the self-incrementing ID of the table. The trigger is to obtain the self-incrementing ID of the table when new data is added (automatically).

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325855936&siteId=291194637