
create table tab1 ( pkey serial not null primary key, name varchar(50) );

create or replace procedure tab1_do_inserts( rowcnt int )
language plpgsql    
as $$
declare
    c integer;
    pkey1 integer;
    pkey2 integer;
begin
    c := 0;
    loop
        insert into tab1 (name) VALUES ('aaa')
            returning tab1.pkey,
                      (select case
                         when tab1.pkey>=(select last_value from public.tab1_pkey_seq)
                              then setval('public.tab1_pkey_seq',tab1.pkey,true)
                         else 0
                       end)
            into pkey1, pkey2; 
        c := c + 1;
        exit when c > rowcnt;
    end loop;
end;
$$;

call tab1_do_inserts(5);

select * from tab1;


