仅当value不为null时,才使用外键引用更新列

时间:2019-02-28 12:00:55

标签: sql database postgresql

我有以下两个表:

CREATE TABLE public.table_b (
    id serial primary key,
    str character varying NOT NULL
);

CREATE TABLE public.table_a (
    id serial primary key,
    mystring character varying NOT NULL,
    foreignstring integer NOT NULL references table_b (id)
);

insert into table_b (str) values ('foreign sample');
insert into table_a (mystring, foreignstring) values ('my sample', (select id from table_b where str = 'foreign sample'));

我想使用以下函数更新table_a的某些值:

CREATE OR REPLACE FUNCTION public.update_row(
    _id int,
    _mystring varchar,
    _fkstr varchar
)
  RETURNS void AS
$BODY$
DECLARE
    _var int;
BEGIN
loop
    select id from table_b where str = _fkstr into _var;
    exit when FOUND;
    insert into table_b (str) values (_fkstr)
    on conflict do nothing
    returning id
    into _var;
    exit when FOUND;
end loop;

update table_a set
    mystring = coalesce(_mystring, mystring),
    foreignstring = _var
where
    id = _id
;

END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;

该函数应仅更新未传递为null的值。如果传递了null值,则不得更改旧值。只要具有外部引用的列没有收到null值,此方法就可以正常工作:

select update_row(1, null, 'foreign example'); -- ok

如果我不想更改列foreignstring并传递一个null值,则该函数调用将失败,因为它试图将null插入到table_b中:

    select update_row(1, null, null); -- fails

仅当传递了非null值时,才如何更新foreignstring,否则保持不变?

0 个答案:

没有答案