pg_get_serial_sequence() 是一个系统函数,用于获取由特定表列使用的序列的名称。
pg_get_serial_sequence() 添加于 PostgreSQL 8.0。
用法
pg_get_serial_sequence ( table text, column text ) → text
请注意,表名将根据常规 SQL 规则进行解析,这意味着表名(以及任何模式限定)必须正确引用;请参见下面的示例。
变更历史
- PostgreSQL 8.0
- 添加于(提交 a0e842d8)
示例
pg_get_serial_sequence() 的基本用法示例
postgres=# CREATE TABLE foo (id SERIAL, val TEXT);
CREATE TABLE
postgres=# \d foo
Table "public.foo"
Column | Type | Collation | Nullable | Default
--------+---------+-----------+----------+---------------------------------
id | integer | | not null | nextval('foo_id_seq'::regclass)
val | text | | |
postgres=# SELECT pg_get_serial_sequence('foo', 'id');
pg_get_serial_sequence
------------------------
public.foo_id_seq
(1 row)
与 currval() 函数一起使用的示例
postgres=# SELECT currval(pg_get_serial_sequence('foo','id')); ERROR: currval of sequence "foo_id_seq" is not yet defined in this session postgres=# INSERT INTO foo VALUES(DEFAULT, 'bar'); INSERT 0 1 postgres=# SELECT currval(pg_get_serial_sequence('foo','id')); currval --------- 1 (1 row)
如果表名和/或列名需要引用,表名必须像 SQL 标识符一样显式引用,而列名必须作为文字字符串提供,例如:
postgres=# CREATE TABLE "FOO" ("ID" SERIAL, val TEXT);
CREATE TABLE
postgres=# SELECT pg_get_serial_sequence('"FOO"', 'ID');
pg_get_serial_sequence
------------------------
public."FOO_ID_seq"
(1 row)
postgres=# SELECT pg_get_serial_sequence(quote_ident('FOO'), 'ID');
pg_get_serial_sequence
------------------------
public."FOO_ID_seq"
(1 row)
参考资料
- PostgreSQL 文档: 系统目录信息函数
