批量重置所有sequence为表已有数据的最大值
可用
####查询所有表对应列上的sequence
select *
from (
select table_schema,
table_name,
column_name,
pg_get_serial_sequence(format('%I.%I', table_schema, table_name), column_name) as col_sequence
from information_schema.columns
where table_schema in ('public', 'upayfn')
) t
where col_sequence is not null;
可用
##生成批量重置sequence为表列上的最大值
with sequences as (
select *
from (
select table_schema,
table_name,
column_name,
pg_get_serial_sequence(table_schema||'.'||table_name, column_name) as col_sequence
from information_schema.columns
where table_schema in ('public', 'upayfn')
) t
where col_sequence is not null
)
select table_schema, table_name, column_name, col_sequence,
'select max('||column_name||') from '||table_schema||'.'||table_name||';' as max_val,
'select setval('''||col_sequence||''' ,(select max('||column_name||') from '||table_schema||'.'||table_name||'))' as reset_seq
from sequences;
####生成批量重置sequence为表列上的最大值
with sequences as (
select *
from (
select table_schema,
table_name,
column_name,
pg_get_serial_sequence(table_schema||'.'||table_name, column_name) as col_sequence
from information_schema.columns
where table_schema in ('public', 'upayfn')
) t
where col_sequence is not null
)
select
'select setval('''||col_sequence||''' ,(select max('||column_name||') from '||table_schema||'.'||table_name||'));' as reset_seq
from sequences;
===============================================
附件参考-不可用
####not in
with sequences as (
select *
from (
select table_schema,
table_name,
column_name,
pg_get_serial_sequence(format('%I.%I', table_schema, table_name), column_name) as col_sequence
from information_schema.columns
where table_schema not in ('pg_catalog', 'information_schema')
) 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 sequence
from maxvals;
####in
with sequences as (
select *
from (
select table_schema,
table_name,
column_name,
pg_get_serial_sequence(format('%I.%I', table_schema, table_name), column_name) as col_sequence
from information_schema.columns
where table_schema in ('public', 'upayfn')
) 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 sequence
from maxvals;