Sequences
A sequence:
- Can automatically generate unique numbers
- Is a shareable object
- Can be used to create a primary key value
- Replace application code
- Speeds up the efficiency of accessing sequence values when cached in memory.
CREATE SEQUENCE Statement Syntax
Define a sequence to generate sequential numbers automatically:
CREATE SEQUENCE sequence [INCREMENT BY n] [START WIT n] [{MAXVALUE n | NOMAXVALUE}] [{MINVALUE n | NOMINVALUE}] [{CYCLE | NOCYCLE}] [{CACHE n | NOCACHE}]
Creating a Sequence
Create a sequence named DEPT_DEPTID_SEQ to be used for the primary key of the DEPARTMENTS table,and Do not use the CYCLE option
CREATE SEQUENCE dept_deptid_seq INCREMENT BY 10 START WITH 120 MAXVALUE 9999 NOCACHE NOCYCLE;
NEXTVAL and CURRVAL Pseudocolumns
NEXTVAL returns the next available sequence value.It returns a unique value every time it is referenced,even for different users.
CURRVAL obtains the current sequence value.
NEXTVAL must be issued for that sequence before CURRVAL contains a value.
使用SEQUENCE
如果首次创建SEQUENCE dept_deptid_seq,执行SELECT dept_deptid_seq.CURRVAL FROM DUAL;会报错
SQL> select dept_deptid_seq.currval from dual; select dept_deptid_seq.currval from dual * ERROR at line 1: ORA-08002: sequence DEPT_DEPTID_SEQ.CURRVAL is not yet defined in this session
必须先执行SELECT dept_deptid_seq.NEXTVAL FROM DUAL;然后再执行SELECT dept_deptid_seq.CURRVAL FROM DUAL;
Caching Sequence Values
- Caching sequence values in memory gives faster access to those values
- Gaps in sequence values can occur when:
- -A rollback occurs
- -The system crashes
- -A sequence is used in another table
Modifying a Sequence
Change the increment value,maximum value,minimum value,cycle option,or cache option,but you can not modify the start with keyword
ALTER SEQUENCE dept_deptid_seq INCREMENT BY 20 MAXIMUM 999999 NOCACHE NOCYCLE;
Guidelines for Modifying a Sequence
- You must be the owner or have the ALTER privilege for the sequence
- Only future sequence numbers are affected
- The sequence must be dropped and re-created to restart the sequence at a different number
- Some validation is performed
Drop Sequence
To remove a sequence ,use the DROP SEQUENCE statement
DROP SEQUENCE dept_deptid_seq;