0

What is a flexible way to create a function returning multiple rows? Im in development of a pg9.4 database, and it is not uncommon to modify the number of columns in the SELECT statements in my functions. However, as Ive learned plpgsql the RETURNS is specified as SETOF . Which is fine as long as the SELECT is a * or specifies all the table's columns in the query.

Is there a way to tell the RETURNS to use a SETOF the columns in the SELECT statement, or something along those lines? I saw that I could use RETURNS TABLE return multiple select , but I was hoping for something more dynamic. Thanks

CREATE TABLE business
(
  retailerid integer NOT NULL,
  retailername character varying(250) NOT NULL,
  CONSTRAINT pkretailerid PRIMARY KEY (retailerid)
)
WITH ( OIDS=FALSE );
INSERT INTO business(retailerid, retailername)
VALUES(1,'Mc Donalds');
INSERT INTO business(retailerid, retailername)
VALUES(2,'Burger King');

CREATE OR REPLACE FUNCTION getretailers()
  RETURNS SETOF business AS
$BODY$
 BEGIN
 RETURN QUERY 
    SELECT retailerid, retailername FROM business;
 END
 $BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100
  ROWS 1000;

SELECT getretailers(); -- works
drop function getretailers();

CREATE OR REPLACE FUNCTION getretailers()
  RETURNS SETOF business AS
$BODY$
 BEGIN
 RETURN QUERY 
    SELECT retailername FROM business;
 END
 $BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100
  ROWS 1000;
SELECT getretailers(); -- err, structure of query does not match return type
3
  • You will need to add some examples - I for one have no idea what you are trying to do. Commented Nov 11, 2016 at 16:35
  • setof expects more than one field to be returned. Commented Nov 11, 2016 at 16:54
  • @mcNets that may be, but I dont believe its the issue here. SETOF requires that you specify some type of schema (table, view) that exactly (except for *) matches the select statement columns. Or you can use TABLE, which is sort of an in-function schema. I was hoping for a way the return schema is automatically derived from the select columns. Thx! Commented Nov 11, 2016 at 17:30

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.