List all sequences in a Postgres db 8.1 with SQL

后端 未结 19 1777
旧时难觅i
旧时难觅i 2020-12-12 11:30

I\'m converting a db from postgres to mysql.

Since i cannot find a tool that does the trick itself, i\'m going to convert all postgres sequences to autoincrement id

19条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-12 11:57

    This function shows the last_value of each sequence.

    It outputs a 2 columns table that says the sequence name plus it's last generated value.

    drop function if exists public.show_sequence_stats();
    CREATE OR REPLACE FUNCTION public.show_sequence_stats()
        RETURNS TABLE(tablename text, last_value bigint) 
        LANGUAGE 'plpgsql'
        COST 100
        VOLATILE 
        ROWS 1000
    AS $BODY$
    declare r refcursor; rec record; dynamic_query varchar;
            BEGIN
                dynamic_query='select tablename,last_value from (';
                open r for execute 'select nspname,relname from pg_class c join pg_namespace n on c.relnamespace=n.oid where relkind = ''S'' order by nspname'; 
                fetch next from r into rec;
                while found 
                loop
                    dynamic_query=dynamic_query || 'select '''|| rec.nspname || '.' || rec.relname ||''' "tablename",last_value from ' || rec.nspname || '.' || rec.relname || ' union all ';
                    fetch next from r into rec; 
                end loop;
                close r; 
                dynamic_query=rtrim(dynamic_query,'union all') || ') x order by last_value desc;';
                return query execute dynamic_query;
            END;
    $BODY$;
    
    select * from show_sequence_stats();
    

提交回复
热议问题