Oracle principle: sequence

 A sequence is an object that generates a unique serial number. It's a bit like the seed identifier in SQL Server, which can be used to achieve self-increment.

CREATE SEQUENCE S_NO    --序列名
START WITH 1            --起始值
INCREMENT BY 1          --自增值
MAXVALUE  200           --最大值
MINVALUE 1              --最小值
NOCYCLE                 --超过最大值是否从头算起
CACHE 10;               --内存中预先分配的序列号

Create sequence requires permission CREATE SEQUENCE;

CACHE 10: Refers to the pre-allocated serial number. For example, when the user wants to take sequence 1, 1~10 will be generated together, so next time sequence 2 is taken, there is no need to perform calculation first, just take sequence 2 directly.

CREATE SEQUENCE S_NO2    --序列名
START WITH 1            --起始值
INCREMENT BY 1 ;         --自增值

select * from user_sequences

You can use user_sequences to view the sequence information created by your own users; you can use dba_sequences to view the sequence information of all users

We can see that the default value of each value, when there is no specified value, MIN_VALUE is 1 by default, MAX_VALUE is 10^28, no loop is performed, and CACHE_SIZE is 20;

When using SEQUENCE, CURRVAL obtains the current sequence; NEXTVAL obtains the next sequence; when using SEQUENCE for the first time, use NEXTVAL to initialize the sequence, otherwise an error will be reported.

At this time, query the sequence s_no information:

Found that LAST_NUMBER has become 11, because your CACHE_SIZE is set to 10

Keep getting the next sequence, and found that in the process, the LAST_NUMBER of S_NO is always 11.

When it gets 11, LAST_NUMBER changes to 21.

Use sequence to realize the self-increment function of the seed field in SQLServer, just use s_no.nextval when insert into;

For example, the student ID is usually composed of the year of enrollment, the professional code and the class seat number, and the automatic generation of the class seat number can use the sequence;

 

Modification sequence: Except for the initial value of START WITH which cannot be modified, everything else can be modified

ALTER SEQUENCE S_NO 
Maxvalue 1000 
Cycle  
INCREMENT BY -6;

You can use CREATE OR REPLECE to rebuild, or set INCREMENT BY to a negative value, and execute the following NEXTVAL.

 

   if sequence is not initialized

     LAST_NUMBER =  Nextval

   else 

     LAST_NUMBER = next sequence number for memory allocation

 

Delete sequence:

DROP SEQUENCE [sequence name]

Guess you like

Origin blog.csdn.net/superSmart_Dong/article/details/104552248