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:
能夠為正(升序)、負整數(降序)。但不能為0。
最高精度28。
最大28位。
必須大於等於起始值且大於等於序列最小值。
NOMAXVALUE: 無最大值(實際為10^27或-1)。default
NOMINVALUE :無最小值(實際為1或-10^26)。Default
CYCLE :指定序列達到最大值或最小值后繼續從頭開始生成。
CACHE :指定數據庫內存中預分配的序列值個數,以便高速獲取。最小cache值為2。
Cache參數最大值為:
(CEIL (MAXVALUE - MINVALUE)) / ABS (INCREMENT)
注意1:假設系統發生問題。全部緩存的沒有被DML語句使用並提交的序列值將丟失。潛在丟失值數量等於cache的數量。
此條件適用於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 含distinctkeyword查詢
· 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.