This is a stored procedure I have converted from MS SQLServer to PostgreSQL. Is there any better way to write it in Postgres. Also what should be the best practices? Any help will be appreciated.
create or replace function GenSerialNo_SP1(tname character varying) returns AS $$
--declare @PK bigint
declare totalRec bigint;
declare getRec bigint;
Begin
--set @PK = 1
set totalRec=-1;
for getRec inselect coalesce(primary_key,0) from STD_SERIAL_NOS
where table_name = tname
loop
open getRec;
fetch next from getRec into totalRec;
close getRec;
deallocate getRec;
end loop;
if totalRec = -1 then
insert into STD_SERIAL_NOS (TABLE_NAME, PRIMARY_KEY) values (tname, 1);
else
update STD_SERIAL_NOS set primary_key = primary_key +1
where table_name = tname;
end if;
end;
$$ language plpgsql;