postgresql 如何将整数转换为串行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12591207/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 00:20:36  来源:igfitidea点击:

How to convert integer to serial

postgresql

提问by drnextgis

I have a table which has a primary key column "gid" and its type is "Integer NOT NULL". I want to convert it into "Serial NOT NULL" so that I can insert some values into this table. I used following commands to convert it into serial:

我有一个表,它有一个主键列“gid”,它的类型是“Integer NOT NULL”。我想将其转换为“Serial NOT NULL”,以便我可以在该表中插入一些值。我使用以下命令将其转换为串行:

CREATE SEQUENCE test_table_gid_seq
        INCREMENT 1
        MINVALUE 1
        MAXVALUE 2147483648 START 1
        CACHE 1;

ALTER TABLE test_table ALTER COLUMN gid
        SET DEFAULT nextval('test_table_gid_seq'::regclass);

This command converted integer to serial. But while I entered some data to the table following error occurred:

此命令将整数转换为串行。但是当我向表中输入一些数据时,发生了以下错误:

ERROR: duplicate key value violates unique constraint "pk_test".

错误:重复的键值违反了唯一约束“pk_test”。

Please help me to solve this. Is there any other method to convert integer to serial?

请帮我解决这个问题。有没有其他方法可以将整数转换为串行?

回答by drnextgis

Select max value of gid column (max_gid):

选择 gid 列的最大值 (max_gid):

SELECT max(gid) FROM test_table;

And use it as start point for sequence (probably, max_gid+1):

并将其用作序列的起点(可能是 max_gid+1):

ALTER SEQUENCE test_table_gid_seq RESTART WITH max_gid;