Postgresql
重命名序列後如何更改 sequence_name 參數(PostgreSQL)
我使用以下命令重命名了一個序列:
ALTER SEQUENCE TableIdSeq RENAME TO NewTableIdSeq;
但是,當我發出
\d NewTableIdSeq
命令時,我得到以下輸出:Sequence "dev.newtableidseq" Column | Type | Value ---------------+---------+--------------------- sequence_name | name | tableidseq <--------------- HASN'T CHANGED!! last_value | bigint | 3 start_value | bigint | 1 increment_by | bigint | 1 max_value | bigint | 9223372036854775807 min_value | bigint | 1 cache_value | bigint | 1 log_cnt | bigint | 30 is_cycled | boolean | f is_called | boolean | t
如您所見,
sequence_name
序列的屬性仍然設置為舊名稱。我怎樣才能在這裡更改名稱?
別擔心。儲存在序列中的序列名稱被忽略。這個欄位在 PostgreSQL 10 中消失了。
您應該重命名序列,然後更改此列的預設值。
讓我生成一個例子:
create sequence tbl_id_seq; create table tbl ( id int default nextval('tbl_id_seq'), f1 int, f2 int ); insert into tbl (f1, f2) values (1,2),(3,4),(5,6); select * from tbl; id | f1 | f2 -: | -: | -: 1 | 1 | 2 2 | 3 | 4 3 | 5 | 6 -- rename sequence alter sequence tbl_id_seq rename to tbl_id_new_seq; -- alter default value alter table tbl alter column id set default nextval('tbl_id_new_seq'); -- restart sequence alter sequence tbl_id_new_seq restart with 1; -- check it by inserting new values insert into tbl (f1, f2) values (1,2),(3,4),(5,6); select * from tbl; id | f1 | f2 -: | -: | -: 1 | 1 | 2 2 | 3 | 4 3 | 5 | 6 1 | 1 | 2 2 | 3 | 4 3 | 5 | 6
現在使用
\d tbl
+-------------------------------------------------------------------------------+ | Table "public.tbl" | +-------------------------------------------------------------------------------+ | Column | Type | Collation | Nullable | Default | +--------+---------+-----------+----------+-------------------------------------+ | id | integer | | | nextval('tbl_id_new_seq'::regclass' | +--------+---------+-----------+----------+-------------------------------------+ | f1 | integer | | | | +--------+---------+-----------+----------+-------------------------------------+ | f2 | integer | | | | +--------+---------+-----------+----------+-------------------------------------+
對於
\d tbl_id_new_seq
:postgres=# \d tbl_id_new_seq; Sequence "public.tbl_id_new_seq" -[ RECORD 1 ]------------------ Type | bigint Start | 1 Minimum | 1 Maximum | 9223372036854775807 Increment | 1 Cycles? | no Cache | 1