鉴于此表:
create table test (
name text primary key
);
我需要编写一个 plpgsql 函数,其变量名称与主键名称冲突,我必须在on conflict
子句中使用它:
create or replace function func(
name text -- this variable name...
) returns void language plpgsql as
$$
begin
insert into test (name) values (name)
on conflict (name) do update -- ...conflicts with this line
set name = func.name;
end;
$$;
这会编译,但随后会引发模棱两可的列引用:
select * from func('one');
ERROR: column reference "name" is ambiguous
LINE 2: on conflict (name) do update
^
DETAIL: It could refer to either a PL/pgSQL variable or a table column.
QUERY: insert into test (name) values (name)
on conflict (name) do update
set name = func.name
CONTEXT: PL/pgSQL function func(text) line 3 at SQL statement
我尝试将完整的列名指定为on conflict (test.name)
哪个不编译,或者((test.name))
哪个编译:
create or replace function func(
name text
) returns void language plpgsql as
$$
begin
insert into test (name) values (name)
on conflict ((test.name)) do -- this fails too
update set name = func.name;
end;
$$;
但它也失败了:
select * from func('two');
ERROR: invalid reference to FROM-clause entry for table "test"
LINE 2: on conflict ((test.name)) do
^
HINT: There is an entry for table "test", but it cannot be referenced from this part of the query.
QUERY: insert into test (name) values (name)
on conflict ((test.name)) do
update set name = func.name
CONTEXT: PL/pgSQL function func(text) line 3 at SQL statement
有解决办法吗?
编辑:我找到了解决方法:
on conflict on constraint test_pkey do update
test_pkey
表名加在哪里_pkey
。我不知道这有多可靠。我仍然想指定列名。