多行的 Postgres 声明类型

Postgres declaration type for multiple rows

我有一个使用 %ROWTYPE 声明的 postgres 函数。当我执行这个函数时,我得到了关于返回多行的失败 "code":"P0003","message":"query returned more than one row"

我可以在没有 returning * into assignments; 语句的情况下成功执行查询。这让我相信 assignments data.assignment%ROWTYPE; 仅适用于一行?

create or replace function assign(order_id int) returns json as $$
declare
 assignments data.assignment%ROWTYPE;
begin
        insert into data.assignment
        (order_item_id, pharmacy_id)
         (
               select oi.id as order_item_id, mci.pharmacy_id
               from api.order_items as oi
               inner join api.min_cost_inventory_items as mci on mci.drug_id = oi.drug_id
               where oi.order_id = 
         )
        returning * into assignments;

        return json_build_object(
          'assignments', assignments
        );
end
$$ security definer language plpgsql;
revoke all privileges on function assign(int) from public;

是的。 %ROWTYPE 不是绝对必要的,但无论如何它只包含一行。你可以制作一个 data.assignment[] 的数组,但是你需要循环来填充它。

您可以将函数简化如下:

create or replace function assign(_order_id int) returns jsonb as $$
  with i as (
    insert into data.assignment
     (order_item_id, pharmacy_id)
    select oi.id as order_item_id, mci.pharmacy_id
      from api.order_items as oi
           inner join api.min_cost_inventory_items as mci 
                   on mci.drug_id = oi.drug_id
                where oi.order_id = _order_id
    returning *
  )
  select jsonb_agg(to_jsonb(i)) from i;
$$ security definer language sql;