我想将记录插入具有可选参数的存储函数中,并返回插入的记录。
表是:
CREATE TABLE partner (
id serial NOT NULL,
name text NOT NULL,
status text not null default 'internal',
active bool not NULL DEFAULT true
);
请注意,列状态和活动状态具有默认值。
存储功能具有必需参数和可选参数。
create or replace function addPartner(pname text, pstatus text = null, pactive bool = null) returns partner as $$
declare
newrecord partner;
begin
insert into partner
(name)
values(pname)
returning * into newrecord;
if pactive is not null then
update partner set active = pactive where id = newrecord.id returning * into newrecord;
end if;
if pstatus is not null then
update partner set status = pstatus where id = newrecord.id returning * into newrecord;
end if;
return newrecord;
end;
$$ language plpgsql;
并调用一个函数如下:
select * from addPartner('customer A', 'external', false);
select * from addPartner('customer B', 'external');
select * from addPartner('customer C');
select * from partner;
在使用所有参数(“客户A”)调用函数的情况下,我需要执行一条插入记录,其中包含必需的参数和可选参数的默认值,然后在此之后,为每个可选参数(或列)插入一条记录(具有默认值)对可选参数值执行更新。总体而言,有1次插入和2次更新。
我想避免在存储的函数中进行这些多次更新,并尽可能在一条SQL语句中插入一条新记录。
一个带有参数值或默认值(如果省略了可选参数)的插入语句。
链接到rextester上的先前代码: https://rextester.com/POZM9812
答案 0 :(得分:0)
使用动态SQL:https://rextester.com/UGA76790
create or replace function addPartner(pname text, pstatus text = null, pactive bool = null) returns partner as $$
declare
newrecord partner;
statement TEXT;
begin
statement := FORMAT(
'INSERT INTO partner (name, status, active) VALUES ($1, %s, %s) RETURNING *',
COALESCE(QUOTE_LITERAL(pstatus), 'DEFAULT'),
COALESCE(QUOTE_LITERAL(pactive), 'DEFAULT')
);
EXECUTE statement
INTO newrecord
USING pname;
return newrecord;
end;
$$ language plpgsql;