PostgreSQL: Structure of query does not match function result type using polymorphic type "anyelement"

StackOverflow https://stackoverflow.com/questions/22834351

Question

Problem: Getting error while returning the selected rows from table using polymorphic type "anyelement".

Error: structure of query does not match function result type.

---Table

CREATE TABLE tes1
(
    rollno integer,
    fname text,
    lname text,
    age integer,
    branch text,
    phno integer,
    email text,
    address text,
    city text,
    state text,
    country text
)

---Function

create or replace function fun_test(column_name varchar,relation_name anyelement)
returns setof anyelement as
$body$
declare
        str varchar;
        grouping varchar;
        additional_column varchar;
        select_query varchar;
begin
       if column_name='fname' then
               str:=quote_ident(column_name);
               additional_column:=' max("address") as addr, max("city") as cty, max("state") as st, max("country") as cntry';
           grouping:='"rollno"'||','||quote_ident(column_name);
   else
           str:=quote_ident(column_name);
           additional_column:=' max("address") as addr, max("city") as cty, max("state") as st, max("country") as cntry';
           grouping:='"rollno"'||','||quote_ident(column_name);
   end if;

   select_query:= 'select rollno,'||str||','||additional_column||' from '||pg_typeof(relation_name)||
   ' group by '|| grouping;

   raise info '%',select_query;

   return query execute select_query;
end;
$body$
language plpgsql;

---Calling function

 select * from fun_test('fname',NULL::test)
Was it helpful?

Solution

Maybe a simple typo?

CREATE TABLE tes1
...

select * from fun_test('fname',NULL::test)

As for the follow up in the comment

Error DETAIL: Returned type text does not match expected type integer in column 4

The error message is pretty obvious. You need to cast the 4th value in your SELECT statement to integer or use text in the type definition. In your current function there are more mismatches between defined type and what you return.

OTHER TIPS

Not sure, but it seems that as you return more than one column, so the return type should be set of record.

 create or replace function fun_test(column_name varchar,relation_name anyelement)
 returns setof record as
 ...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top