0

我是 Postgres 的新手。我使用 Pgadmin III,我需要在“更改序列”的状态中参数化一个值。我试图执行这段代码:

select coalesce(MAX(ID)+1,1) as max into myTempTable from myTable;
EXECUTE immediate 'ALTER SEQUENCE mySequence INCREMENT BY 1 START WITH ' || max || ' MINVALUE 1 NO CYCLE';

但它不起作用。怎么了?我需要将它封装在一个函数中吗?谢谢你。D.

4

2 回答 2

1

要将值设置为手动排序,您可以使用ALTER SEQUENCE seq_name RESTART WITH value

关于你的例子,你需要这样的东西:

CREATE SEQUENCE testseq;

DO $$
DECLARE
    maxid INT;
BEGIN
    SELECT coalesce(MAX(ID)+1,1) FROM myTable INTO maxid;
    EXECUTE 'ALTER SEQUENCE testseq RESTART WITH '|| maxid;
END;
$$ LANGUAGE PLPGSQL
于 2017-03-05T17:28:01.287 回答
0

无需动态 SQL。

只需创建序列,然后更改当前值:

create sequence mysequence increment by 1 minvalue 1 no cycle;
select setval('mysequence', (select coalesce(MAX(id)+1,1) from mytable));

您可能还希望将该序列设为该列的默认值:

alter table mytable alter column id
   set default nextval('mysequence');  

alter sequence mysequence owned by mytable.id;
于 2017-03-05T19:31:07.373 回答