Thread: problem selecting from function

problem selecting from function

From
Rikard Pavelic
Date:
Hi!

Can someone help me with this problem.

When I select from this function I get an error

ERROR: record "red" has no field "id"
SQL state: 42703
Context: PL/pgSQL function "select_ex1" line 4 at assignment

Here is the code

create table example1(
id serial primary key,
name1 varchar(10),
value1 int);

insert into example1 values(1,'abc',2);
insert into example1 values(3,'def',5);

create function select_ex1(out id int, out name1 varchar, out value1
int) returns setof record as
$$
declare red record;
begin
    for red in select id, name1, value1 from example1 LOOP
        id=red.id;
        name1=red.name1;
        value1=red.value1;
        return next;
    end LOOP;
end
$$ language plpgsql;

and
select * from select_ex1();

It seems to me that postgres doesn't like returning parameter name
and if I change function to
create function select_ex1(out id1 int, out name2 varchar, out value2 int)
then everything is ok.

Regards,
Rikard

Re: problem selecting from function

From
Michael Fuhr
Date:
On Fri, Apr 06, 2007 at 03:52:17AM +0200, Rikard Pavelic wrote:
> When I select from this function I get an error
>
> ERROR: record "red" has no field "id"
[...]
> create function select_ex1(out id int, out name1 varchar, out value1
> int) returns setof record as
> $$
> declare red record;
> begin
>    for red in select id, name1, value1 from example1 LOOP
>        id=red.id;
>        name1=red.name1;
>        value1=red.value1;
>        return next;

The columns in the select list match the parameter names so you're
selecting the parameters, not the columns in example1.  The query
is effectively:

   for red in select NULL, NULL, NULL from example1 loop

The code should work if you qualify the columns:

   for red in select e.id, e.name1, e.value1 from example1 e loop

--
Michael Fuhr