序列使用
更新(xin)時間(jian) 2025-02-14 10:24:37
最近更新時(shi)間(jian): 2025-02-14 10:24:37
分享文(wen)章
本頁介紹天翼云(yun)TeleDB數據(ju)庫的序列使用方法。
序(xu)列創(chuang)建與訪(fang)問
創(chuang)建序列
teledb=# create sequence t_seq; CREATE SEQUENCE建立序列(lie),不存在時才創建
teledb=# create sequence if not exists t_seq; NOTICE: relation "t_seq" already exists, skipping CREATE SEQUENCE查看(kan)序(xu)列當(dang)前的使(shi)用狀(zhuang)況
teledb=# select * from t_seq; last_value | log_cnt | is_called ------------+---------+----------- 1 | 0 | f (1 row)獲取(qu)序列(lie)的下(xia)一個值
teledb=# select nextval('t_seq'); nextval --------- 1 (1 row)獲(huo)取序列(lie)的當前值,這個(ge)需要在(zai)訪問nextval()后(hou)才能使用
teledb=# select currval('t_seq'); currval --------- 1 (1 row)設置序列當前值(zhi)
teledb=# select setval('t_seq',2); setval -------- 2 (1 row)
序列在DML 中(zhong)使用
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)序列作(zuo)為字(zi)段(duan)的默認值使用
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)序列作為(wei)字段類(lei)型使(shi)用
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)刪除序列
存在依賴對象(xiang)時,無法刪除,可通過cascade級聯(lian)刪除。
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刪(shan)除序列,不存(cun)在時跳(tiao)過
teledb=# drop sequence if exists t_seq;
NOTICE: sequence "t_seq" does not exist, skipping
DROP SEQUENCE