do --check seq not in sync
$$
declare
 _r record;
 _i bigint;
 _m bigint;
begin
  for _r in (
    Select
      DISTINCT(constraint_column_usage.table_name) as tablename,
      constraint_column_usage.column_name as idname,
      replace(replace(columns.column_default,'''::regclass)',''),'nextval(''','') as seqname,
            columns.table_schema as schamename
      from information_schema.constraint_column_usage, information_schema.columns
      where constraint_column_usage.table_schema ='public' AND
      columns.table_schema = 'public' AND columns.table_name=constraint_column_usage.table_name
      AND constraint_column_usage.column_name = columns.column_name
      AND columns.column_default is not null
   ) loop
    execute format('select last_value from %I.%s',_r.schamename,_r.seqname) into _i;
    execute format('select max(%I) from %I.%I',_r.idname,_r.schamename,_r.tablename) into _m;
    if coalesce(_m,0) > _i then
      raise info '%',concat('changed: ',_r.tablename||'_Id_seq',' from:',_i,' to:',_m+1);
      execute format('alter sequence %I.%s restart with %s',_r.schamename,_r.seqname,_m+1);
    end if;
  end loop;

end;
$$
;

 

 posted on 2021-12-09 11:21  絆τ  阅读(412)  评论(0编辑  收藏  举报