• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

pgsql批量修改sequences的start方式

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

修改为指定值

DO $$DECLARE r record;
BEGIN
FOR r IN SELECT sequence_name FROM information_schema."sequences"
LOOP
 EXECUTE 'ALTER SEQUENCE '|| r.sequence_name ||' restart WITH 10000';
END LOOP;
END$$;

根据表的id修改

DO $$
DECLARE 
 r record;
 start_value integer := 0;
BEGIN
FOR r IN SELECT tablename||'_id_seq' AS sequence_name, tablename FROM pg_tables WHERE schemaname = 'public'
LOOP
 EXECUTE 'SELECT max(id)+1 AS max_value FROM ' || r.tablename INTO start_value;
 IF start_value IS NULL THEN start_value:= 1;
 END IF;
 RAISE NOTICE 'start_value % %', r.tablename,start_value;
 EXECUTE 'ALTER SEQUENCE '|| r.sequence_name ||' restart WITH ' || start_value;
END LOOP;
END$$;

补充:postgresql 13 数据库 sequence 的 maxvalue 最大值是多少?

os: centos 7.8.2003

db: postgresql 13.0

版本

# cat /etc/centos-release
CentOS Linux release 7.8.2003 (Core)
# su - postgres
Last login: Thu Oct 15 09:59:33 CST 2020 on pts/1

ppostgres@nodepg13-> psql -c "select version();"
             version             
---------------------------------------------------------------------------------------------------------
 PostgreSQL 13.0 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-39), 64-bit
(1 row)

create sequence

$ psql

postgres=# create sequence seq_1;
CREATE SEQUENCE
postgres=# select c.relname,c.relkind,s.* from pg_class c,pg_sequence s where c.oid=s.seqrelid;
 relname | relkind | seqrelid | seqtypid | seqstart | seqincrement |  seqmax  | seqmin | seqcache | seqcycle 
---------+---------+----------+----------+----------+--------------+---------------------+--------+----------+----------
 seq_1 | S  | 40968 |  20 |  1 |   1 | 9223372036854775807 |  1 |  1 | f
(1 row)
seqmax = 9223372036854775807

maxvalue
NO MAXVALUE
The optional clause MAXVALUE maxvalue determines the maximum value for the sequence. If this clause is not supplied or NO MAXVALUE is specified, then default values will be used. The default for an ascending sequence is the maximum value of the data type. The default for a descending sequence is -1.

那就需要查看下 bigint 的值

以上为个人经验,希望能给大家一个参考,也希望大家多多支持极客世界。如有错误或未考虑完全的地方,望不吝赐教。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap