CREATE SEQUENCE 语句用来创建序列,语法格式如下:
CREATE SEQUENCE sequence_name
[MINVALUE value | NOMINVALUE]
[MAXVALUE value | NOMAXVALUE]
[START WITH value]
[INCREMENT BY value]
[CACHE value | NOCACHE]
[ORDER | NOORDER]
[CYCLE | NOCYCLE];
其中,MINVALUE 和 MAXVALUE 指定最小值和最大值;START WITH 指定起始值;INCREMENT BY 指定步长,可以为负数,默认是1;CACHE 是为了性能缓存部分序列值,并发高的时候使用;CYCLE 指定序列值是否循环,如果循环,需要指定最大值或最小值。
示例:创建序列,实现表的列自增。
obclient> create table t1(id number not null primary key, name varchar(50) , gmt_create date not null default sysdate);
Query OK, 0 rows affected (0.07 sec)
obclient> create sequence seq_t1 start with 10000 increment by 1 cache 50 nocycle;
Query OK, 0 rows affected (0.04 sec)
obclient> insert into t1(id,name) values(seq_t1.nextval, 'A');
Query OK, 1 row affected (0.02 sec)
obclient> insert into t1(id,name) values(seq_t1.nextval, 'B');
Query OK, 1 row affected (0.00 sec)
obclient> insert into t1(id,name) values(seq_t1.nextval, 'C');
Query OK, 1 row affected (0.00 sec)
obclient> select * from t1;
+-------+------+---------------------+
| ID | NAME | GMT_CREATE |
+-------+------+---------------------+
| 10000 | A | 2020-04-02 18:30:29 |
| 10001 | B | 2020-04-02 18:30:34 |
| 10002 | C | 2020-04-02 18:30:39 |
+-------+------+---------------------+
3 rows in set (0.01 sec)
序列创建成功后,可以通过 USER_SEQUENCES、ALL_SEQUENCES、DBA_SEQUENCES 视图查看自己创建的序列。
obclient> select * from user_sequences \G
*************************** 1. row ***************************
SEQUENCE_NAME: SEQ_T1
MIN_VALUE: 1
MAX_VALUE: 9999999999999999999999999999
INCREMENT_BY: 1
CYCLE_FLAG: N
ORDER_FLAG: N
CACHE_SIZE: 50
LAST_NUMBER: 10100
1 row in set (0.00 sec)
obclient>