这是我从 MS SQLServer 转换到 PostgreSQL 的存储过程。有没有更好的方法在 Postgres 中编写它。还有什么应该是最佳实践?任何帮助将不胜感激。
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;
最佳答案
它看起来像一个 UPSERT ,但您不需要任何游标即可实现。
假设 STD_SERIAL_NOS.table_name
上有一个唯一索引,一个(希望如此)正确的版本(包括处理插入时的竞争条件)将是:
create or replace function GenSerialNo_SP1(tname character varying) returns void
as $$
begin
loop
begin
update STD_SERIAL_NOS set primary_key = primary_key +1
where table_name = tname;
exit when found; -- exit loop if the row exists, otherwise insert it
insert into STD_SERIAL_NOS (TABLE_NAME, PRIMARY_KEY)
values(tname,1);
exception WHEN unique_violation THEN
-- the insert conflicts, let's go back to the update in the next loop iteration
end;
end loop;
end;
$$ language plpgsql;
关于sql - 编写 PostgreSQl 函数的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13720365/