我想创建一个返回类似表格结果的 PSQL 函数。我的函数定义如下所示:
create or replace function myfunc1()
returns table(id varchar(50), title varchar(50))
as $$
begin
return query select id, title from books;
end;
$$ language plpgsql;
但是,当我调用该函数时,出现此错误:
ERROR: column reference "id" is ambiguous LINE 1: select id, title from books ^ DETAIL: It could refer to either a PL/pgSQL variable or a table column.
显然,这是因为我在返回表和目标表中都使用了列名“id”。最简单的解决方案是更改列名称。但我来这里是为了寻找一种方法,让我可以使用我想要的列名称。此外,更改名称会使我的代码变得奇怪,并且其他人难以理解。
最佳答案
通过限定列名消除歧义:
create or replace function myfunc1()
returns table(id varchar(50), title varchar(50)) as
$$
select books.id, books.title from books;
$$ language sql stable;
关于database - Postgresql 函数中的列命名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6000194/