How to create sequence using starting value from query?

别说谁变了你拦得住时间么 提交于 2019-12-11 13:23:54

问题


In database migration script (psql) I want to create sequence starting from certain value queried from table, like:

CREATE SEQUENCE book_id_seq START ( SELECT MAX(id) + 1 FROM book.book );

or tried to set \set start (SELECT MAX(id) + 1 FROM book.book) to use variable like:

CREATE SEQUENCE book_id_seq START :'start';

But using \set did not inerpret the query.

Another way setting variable did not work also

start := SELECT MAX(id) + 1 FROM book.book;

gave error:

ERROR:  syntax error at or near ":="
LINE 1: start := SELECT MAX(id) + 1 FROM book.book;

Selecting value INTO does not help also, because accessing needs another SELECT query.

Using static value works fine:

\set start 33
CREATE SEQUENCE book_id_seq START :'start'::int;

How to use dynamic starting value?

Postgres 9.6


回答1:


you can use setval() after you created the sequence:

CREATE SEQUENCE book_id_seq;
select setval('book_id_seq', (SELECT MAX(id) + 1 FROM book.book));


来源:https://stackoverflow.com/questions/50411113/how-to-create-sequence-using-starting-value-from-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!