Chapter 11-Creating Other Schema Objects ---Sequence

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;

 

转载于:https://www.cnblogs.com/arcer/archive/2013/04/10/3012236.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值