ORACLE SEQUENCE 详解
1. About Sequences(关于序列)
序列是数据库对象一种。多个用户可以通过序列生成连续的数字以此来实现主键字段的自动、唯一增长,并且一个序列可为多列、多表同时使用。
序列消除了串行化并且提高了应用程序一致性。(想象一下没有序列的日子怎么办?)
2. Creating Sequences(创建序列)
To create a sequence inyour own schema, you must have the CREATE
SEQUENCE
system privilege. 在自己模式下创建序列需要create sequence权限
To create a sequence inanother user's schema, you must have the CREATE
ANY
SEQUENCE
system privilege. 在其他用户模式下创建序列需要create any sequence权限。
语法:Syntax
如果不加条件语句,默认创建的序列格式如下:
-- Create sequence
create sequence SEQ_T
minvalue 1
maxvalue 999999999999999999999999999
start with 1
increment by 1
cache 20;
语义Semantics:
INCREMENT BY:指定序列增长步长。可以为正(升序)、负整数(降序),但不能为0。最高精度28。
MAXVALUE :指定序列最大值。最大28位。必须大于等于起始值且大于等于序列最小值。
NOMAXVALUE: 无最大值(实际为10^27或-1)。default
NOMINVALUE :无最小值(实际为1或-10^26)。Default
CYCLE :指定序列达到最大值或最小值后继续从头开始生成。
CACHE :指定数据库内存中预分配的序列值个数,以便快速获取。最小cache值为2。
Cache参数最大值为:
(CEIL (MAXVALUE - MINVALUE)) / ABS (INCREMENT)
注意1:如果系统发生故障,所有缓存的没有被DML语句使用并提交的序列值将丢失。潜在丢失值数量等于cache的数量。
ORDER :指定order条件保证序列按请求顺序生成。此条件适用于RAC环境。
例子:
CREATE SEQUENCE customers_seq
START WITH 1000
INCREMENT BY 1
NOCACHE
NOCYCLE;
注意2:带有cycle条件序列当达到最大值后,下一个值从最小值minvalue开始循环!
CREATE SEQUENCE seq1
START WITH 200
INCREMENT BY 10
MAXVALUE 200
CYCLE
NOCACHE;
SELECT seq1.nextval FROM dual;
结果:1
3. ALTER SEQUENCE(修改序列)
前提:
The sequence must be in your own schema, or youmust have the ALTER
object privilege on
the sequence, or you must have the ALTER
ANY
SEQUENCE
systemprivilege.
修改自己模式序列需要alter object权限,修改其他模式序列需要alter any sequence权限。
语法:
语义:
1)如果想以不同的数字重新开始序列,必须删除重建。
SQL> alter sequence seq_t start with 2;
alter sequence seq_t start with 2
*
ERROR at line 1:
ORA-02283: cannot alter starting sequencenumber
2)修改的maxvalue必须大于序列当前值。
SQL> alter sequence seq_t maxvalue 1;
alter sequence seq_t maxvalue 1
*
ERROR at line 1:
ORA-04004: MINVALUE must be less than MAXVALUE
例子:
ALTER SEQUENCE customers_seq
MAXVALUE 1500;
ALTER SEQUENCE customers_seq
CYCLE
CACHE 5;
4. DROP SEQUENCE(删除序列)
前提:
Thesequence must be in your own schema or you must have the DROP ANY SEQUENCE system privilege.
删除序列必须要有drop any sequence权限
语法:
例子:
DROP SEQUENCE oe.customers_seq;
5. NEXTVAL and CURRVAL的使用限制
CURRVAL
and NEXTVAL
can be used in the following places:
· VALUES
clause of INSERT
statements
· The SELECT
list of a SELECT
statement
· The SET
clause of an UPDATE
statement
CURRVAL
and NEXTVAL
cannot be used in these places: 不能用于以下场景
· A subquery 子查询
· A view query or materialized view query 视图或物化视图查询
· A SELECT
statement with the DISTINCT
operator 含distinct关键字查询
· A SELECT
statement with a GROUP
BY
or ORDER
BY
clause带order by 查询语句
· A SELECT
statement that is combined with another SELECT
statement with the UNION,
INTERSECT
, or MINUS
set operator含union, interest,minus操作符
· The WHERE
clause of a SELECT
statement用在where条件中
· DEFAULT
value of a column in a CREATE
TABLE
or ALTER
TABLE
statement 列的默认值
· The condition of a CHECK
constraint check约束
--------------------------------------
Dylan Presents.