Question

I'm looking for a way to define a postgres function that allows to return untyped row values. For argument sake, let's assume the following tables exists:

create table foo(
  id serial primary key,
  value1 varchar(255),
  value2 int,
  value3 datetime,
  value4 boolean
);

We also have a function that allows us to return the result for some columns (this is a rather contrived example, but in reality, a lot of joins happen internally which I'd like to minimise by using only relevant columns):

create or replace function foo_func(col1 text, col2 text) returns 
  table(?, ?) as 
$$
declare 
sql text;
begin
  sql := 'select ' || col1 || ', ' || col2 || ' from foo'
  return execute sql;
end
$$ language plpgsql;

Since the column values depend on the selected column argument, the return table cannot be defined upfront. Is there any way of returning the rows without specifying their values? I've looked at returning a cursor instead, but I'm unsure whether this would be the best option.

(the postgresql version can be defined)

Était-ce utile?

La solution

You need to return setof record (ref).

create or replace function foo_func(col1 text, col2 text) returns 
  setof record as 
$$
declare 
sql text;
r record;
begin
  sql := 'select ' || col1 || ', ' || col2 || ' from foo';
  for r in execute sql
  loop
    return next r;
  end loop;
  return;
end
$$ language plpgsql;

The problem is that you must declare the column types outside the function:

SELECT * from foo_func('value1','value2') as (a varchar(255),b int);

If the declaration mismatches you'll get an error:http://sqlfiddle.com/#!12/ce8b0/3

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top