使用多个复合输出参数调用PostgreSQL函数

时间:2012-04-05 08:10:27

标签: sql database function postgresql plpgsql

我想在PostgreSQL 9.1中定义一个函数,它接受复合类型的多个INOUT参数,但我不知道如何调用它。

例如

CREATE TYPE my_type_a AS (a integer, b float);
CREATE TYPE my_type_b AS (c boolean, d varchar(5));

CREATE FUNCTION my_complex_func(INOUT a my_type_a, INOUT b my_type_b)
RETURNS RECORD
'...'
LANGUAGE plpgsql;

定义语句执行得很好,但我不知道如何调用这个函数!我试过了:

SELECT INTO a, b
    a, b FROM my_complex_func(a, b);

但这会出错:

ERROR:  record or row variable cannot be part of multiple-item INTO list

1 个答案:

答案 0 :(得分:3)

我认为它与您的输入类型或它们的数量无关。

不要返回RECORD,返回真正的复合类型(用CREATE TYPE定义)。

错误record or row variable cannot be part of multiple-item INTO list是因为你试图将ROW嵌套在另一条ROW中。

这应该有效:

CREATE TYPE my_type_a AS (a integer, b float);
CREATE TYPE my_type_b AS (c boolean, d varchar(5));
CREATE TYPE ret_type  AS (w integer, v boolean);

CREATE FUNCTION my_complex_func(INOUT a my_type_a, INOUT b my_type_b)
RETURNS ret_type as $$
 ...
$$ LANGUAGE plpgsql;

然后你可以这样做:

SELECT INTO a, b 
  (x.comp).w, (x.comp).v 
  FROM (select my_complex_func(j, i) as comp) x;

这个具体的例子对我有用:

create type smelly1 as (a integer, b text);
create type smelly2 as (a boolean, b float);
create type rettype as (w integer, v boolean);
create function foo_func(n smelly1, m smelly2) returns rettype as $$
declare
  f_ret rettype;
begin
   f_ret.w := n.a;
   f_ret.v := m.a;
   return f_ret;
end;
$$ language plpgsql;

select (x.comp).w, (x.comp).v from 
  (select foo_func('(4, hello)'::smelly1, '(true,3.14)'::smelly2) as comp) x;

返回:

 w | v 
---+---
 4 | t
(1 row)