Solve the problem of primary key conflict when Oracle auto-increment primary key is inserted

Solve the problem of primary key conflict when Oracle auto-increment primary key is inserted
Description: You insert records into a table with auto-increment primary key, but encounter a primary key conflict error. This may be because the initial value of the auto-increment primary key you set is already used by existing records in the table.

Resolution and Analysis Steps

Here we take the GZGL_NOTICE table as an example, the ID in the table is an auto-incrementing attribute
//Check the sequence name in the table (the sequence name generally set is similar to the original table name)
SELECT sequence_name FROM user_sequences;

sequence_name 
----------------------------
GZGL_SEQ_NOTICE_ID
SEQ_SS_DEPARTMENT
SEQ_SS_QUESTIONTYPE
SEQ_SS_USER
-----------------------


//GZGL_NOTICE table ID auto-increment sequence name is GZGL_SEQ_NOTICE_ID
//View the next value of the current sequence GZGL_SEQ_NOTICE_ID
SELECT GZGL_SEQ_NOTICE_ID.NEXTVAL FROM DUAL;

GZGL_SEQ_NOTICE_ID.NEXTVAL
----------------------------------
460

//View the maximum ID value of the table GZGL_NOTICE
SELECT MAX(ID) FROM GZGL_NOTICE;

MAX(ID)
-----------------------------------
1450

//Analysis: Here it is found that the value of MAX(ID) is larger than the next value of the sequence GZGL_SEQ_NOTICE_ID, there is obviously a problem, and the value of GZGL_SEQ_NOTICE_ID needs to be increased//Set the incremental value of the sequence to ensure that the next execution value is greater than the current
database The largest ID in the list should be larger than the result of MAX(ID)-GZGL_SEQ_NOTICE_ID.NEXTVAL. The above value is 1450-460=990. We can take 1000
ALTER SEQUENCE GZGL_SEQ_NOTICE_ID Increment By 1000;

//View the next value of the set sequence GZGL_SEQ_NOTICE_ID
SELECT GZGL_SEQ_NOTICE_ID.NEXTVAL FROM DUAL;

GZGL_SEQ_NOTICE_ID.NEXTVAL
----------------------------------
1460

//Modify the sequence increment value to the original increment by 1
ALTER SEQUENCE GZGL_SEQ_NOTICE_ID Increment By 1;
//Check the next value of the set sequence GZGL_SEQ_NOTICE_ID
SELECT GZGL_SEQ_NOTICE_ID.NEXTVAL FROM DUAL;

GZGL_SEQ_NOTICE_ID.NEXTVAL
----------------------------------
1461

Guess you like

Origin blog.csdn.net/qq_38387996/article/details/129879053