1

I have the query for example "select id, field1, field2 from table1" (id and field1 are integer and field2 is varchar) and I need call the query from function and return result as is.

CREATE OR REPLACE FUNCTION get_all_record()
  RETURNS TABLE(id integer , field2 varchar(20)) AS
$$                                                  
BEGIN
    EXECUTE 'SELECT table1.id, table1.field2 FROM table1' INTO id, field2;
    RETURN;
END;
$$
  LANGUAGE plpgsql

but this solution returns only one record in one field. How can I correct it?

2
  • You'll want to use RETURN QUERY instead of EXECUTE '...' INTO. Commented Feb 26, 2016 at 17:28
  • JNevill, but if I use RETURN QUERY instead of EXECUTE '...' INTO the function return all records in one field like text "(value1, value2)" Commented Feb 26, 2016 at 18:18

1 Answer 1

2

Try this:

CREATE OR REPLACE FUNCTION get_all_record(OUT id integer, OUT field2 varchar(20))
RETURNS SETOF record
AS $$
BEGIN
    RETURN QUERY SELECT table1.id, table1.field2 FROM tiers;
END;
$$
LANGUAGE plpgsql;
Sign up to request clarification or add additional context in comments.

2 Comments

I need function without parameters
@ViKo Function without parameters returning rowset called view ;) Seriously out parameters just provides result structure and you should use this function like select * from get_all_record() without parameters specifying. @PeterEisentraut your example can be simplified a bit using language sql instead of plpgsql.

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.