如何使用CTE在PostgreSQL中插入多行(WITH)

时间:2019-04-23 06:36:55

标签: sql postgresql function

我正在尝试编写一个接收ID(posts)数组的函数,
并将它们全部插入到另一个表(offer)中。
我需要新创建的行(offers)中的ID,以便以后进行更多处理。

使用WITH

时出现错误
create function foo (post_ids text[])
returns text[]
as $$
  with
  offer_ids as (insert into app.offer (user_email, post_id)
                  values ('a@a.com', unnest(foo.post_ids))
                  returning id),
  ...
  select array_agg(id) from offer_ids;
$$ language sql security definer;

错误

ERROR:  more than one row returned by a subquery used as an expression

如何从WITH返回多行并在以后使用?

1 个答案:

答案 0 :(得分:3)

我认为错误不是来自CTE部分,而是来自INSERT部分。诸如unnest之类的集合返回函数必须用作SELECT语句的一部分:

with offer_ids as (
     insert into app.offer (user_email, post_id)
     select 'a@a.com', f.pid
     from unnest(foo.post_ids) as f(pid)
     returning id
),
...
select array_agg(id) 
from offer_ids;