序列使用
更新時間 2025-02-05 09:37:09
最近更新時間: 2025-02-05 09:37:09
分享文章
本頁介紹天翼云TeleDB數據庫的序列使用方法。
序列創建與訪問
- 創建序列
teledb=# create sequence t_seq; CREATE SEQUENCE - 建立序列,不存在時才創建
teledb=# create sequence if not exists t_seq; NOTICE: relation "t_seq" already exists, skipping CREATE SEQUENCE - 查看序列當前的使用狀況
teledb=# select * from t_seq; last_value | log_cnt | is_called ------------+---------+----------- 1 | 0 | f (1 row) - 獲取序列的下一個值
teledb=# select nextval('t_seq'); nextval --------- 1 (1 row) - 獲取序列的當前值,這個需要在訪問nextval()后才能使用
teledb=# select currval('t_seq'); currval --------- 1 (1 row) - 設置序列當前值
teledb=# select setval('t_seq',2); setval -------- 2 (1 row)
序列在DML 中使用
teledb=# insert into t_update values(nextval('t_seq'),'teledb');
INSERT 0 1
teledb=# select * from t_update;
id | name | age
----+---------+-----
3 | teledb |
(1 row)
序列作為字段的默認值使用
teledb=# alter table t_update alter column id set default nextval('t_seq');
ALTER TABLE
teledb=# insert into t_update(name) values('seqval');
INSERT 0 1
teledb=# select * from t_update;
id | name | age
----+---------+-----
3 | teledb |
4 | seqval |
(2 rows)
序列作為字段類型使用
teledb=# create table t (id serial not null,nickname text);
CREATE TABLE
teledb=# insert into t(nickname) values('seq_val');
INSERT 0 1
teledb=# select * from t;
id | nickname
----+----------
1 | seq_val
(1 row)
刪除序列
存在依賴對象時,無法刪除,可通過cascade級聯刪除。
teledb=# drop sequence t_seq;
ERROR: cannot drop sequence t_seq because other objects depend on it
DETAIL: default for table t_update column id depends on sequence t_seq
HINT: Use DROP ... CASCADE to drop the dependent objects too.
teledb=# drop sequence t_seq cascade;
NOTICE: drop cascades to default for table t_update column id
DROP SEQUENCE
刪除序列,不存在時跳過。
teledb=# drop sequence if exists t_seq;
NOTICE: sequence "t_seq" does not exist, skipping
DROP SEQUENCE