一次 select 中的多项分配

Multiple assignments in a single select

我在 PostgreSQL 中编写了一个函数,我希望使用单个 select 语句为变量分配多个值。我已经声明了一些变量并使用 select 我希望为函数主体中的这些变量赋值。请在函数主体下方找到:

BEGIN        
select SUM(quantity) into v_quantity, MAX(price) into v_price from trade where id=4;
END

当我编译函数时出现以下错误

ERROR:  "max" is not a known variable
LINE 20:     select SUM(quantity) into v_quantity, max(price) into v_...

可能是什么原因? PostgreSQL 是否不允许通过单个 select 进行多次赋值?

您可以使用 record 类型的变量来代替:

...
declare
    rec record;
begin      
    select sum(quantity) as v_quantity, max(price) as v_price into rec from trade where id=4;
    if rec.v_quantity > 100 then
    ...

是的。要让它工作,你应该只有一个 select 列表和一个 INTO 子句,如下所示:

BEGIN        
  select SUM(quantity), MAX(price) into v_quantity, v_price from trade where id=4;
END