栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何批量更新所有表的序列ID postgreSQL

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何批量更新所有表的序列ID postgreSQL

由于@a_horse_with_no_name答案在我的情况下不起作用(SQL文件可能有问题),因此我修改了下面的查询,在我的情况下起作用。

with sequences as (  select *  from (    select table_schema,table_name,column_name,replace(replace(replace(column_default, '::regclass)', ''), '''', ''), 'nextval(', 'public.') as col_sequence    from information_schema.columns    where table_schema not in ('pg_catalog', 'information_schema') and column_default ILIKE 'nextval(%'  ) t  where col_sequence is not null), maxvals as (  select table_schema, table_name, column_name, col_sequence,          (xpath('/row/max/text()',  query_to_xml(format('select max(%I) from %I.%I', column_name, table_schema, table_name), true, true, ''))          )[1]::text::bigint as max_val  from sequences) select table_schema,        table_name,        column_name,        col_sequence,       coalesce(max_val, 0) as max_val,       setval(col_sequence, coalesce(max_val, 1)) --<< this will change the sequencefrom maxvals;

我只是更改

pg_get_serial_sequence(format('%I.%I', table_schema, table_name),column_name) as col_sequence
replace(replace(replace(column_default,'::regclass)', ''), '''', ''), 'nextval(', 'public.') as col_sequence

也许我的查询不是很好,我应该使用正则表达式而不是多个替换。但就我而言,这是100%可行的。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/441623.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号