Generate primary key values using sequences.
Sequence is a database object that can be used by multiple users to generate a series of unique numbers. Sequence definition is stored in the data dictionary. You can use sequence to automatically generate the key value of a primary key by providing a sequence table with unique values. When a sequence is called for the first time, it returns a predetermined value. In each subsequent query, the sequence will generate a value that increases according to the specified increment. The sequence can be cyclically or continuously increased until the specified maximum value is reached.
Copy codeThe Code is as follows:
-- Create sequence
Create sequence seq_on_test
Increment by 1
Start with 1
Nomaxvalue
Nocycle
Nocache;
-- Create a table
Drop table test;
Create table test (
ID integer
, Stu_name nvarchar2 (4)
, Stu_age number
);
-- Insert data
Insert into test values (seq_on_test.nextval, 'Mary ', 15 );
Insert into test values (seq_on_test.nextval, 'Tom ', 16 );
Select * from test;
-- Result
/*
1 Mary 15
2 Tom 16
*/
-- Two methods of seq
Select seq_on_test.currval from dual;
Select seq_on_test.nextval from dual;
-- Result
/*
2
3
*/