【发布时间】:2018-10-31 10:42:21
【问题描述】:
我是使用 PL/pgSQL 的新手,我正在尝试创建一个函数,该函数将查找现有行的 ID,或者在未找到时插入新行并返回新行ID。
下面函数中包含的查询本身可以正常工作,并且函数可以正常创建。但是,当我尝试运行它时,我收到一条错误消息,指出“错误:列引用“id”不明确”。谁能找出我的问题,或者提出更合适的方法来解决这个问题?
create or replace function sp_get_insert_company(
in company_name varchar(100)
)
returns table (id int)
as $$
begin
with s as (
select
id
from
companies
where name = company_name
),
i as (
insert into companies (name)
select company_name
where not exists (select 1 from s)
returning id
)
select id
from i
union all
select id
from s;
end;
$$ language plpgsql;
这就是我调用函数的方式:
select sp_get_insert_company('TEST')
这是我得到的错误:
SQL 错误 [42702]:错误:列引用“id”不明确
详细信息:它可以引用 PL/pgSQL 变量或表列。
其中:PL/pgSQL 函数 sp_get_insert_company(character varying) SQL 语句的第 3 行
【问题讨论】:
-
嗯,我认为 PL SQL 是在询问您返回的是哪个
id?s.id?i.id? -
@JacobH 我刚刚尝试了来自sticky bit的答案,以定义
id的含义(s.id或i.id),但它并没有解决问题。我认为这不会有什么不同,因为我union正在处理两个单独的查询。 -
尝试为所有内容设置别名,包括 CTE(例如:
select c.id from companies c where c.name = company_name),看看这是否能让您更接近。
标签: sql postgresql