I am trying to create a POSTGRESQL function which would first INSERT some data in a table using WHILE LOOP and then SELECT the results of this table.
This is an sql example:
CREATE OR REPLACE FUNCTION get_levels_test (maxlevel int) RETURNS SETOF list_of_levels AS $$
DECLARE
level int = 1;
BEGIN
TRUNCATE list_of_levels;
WHILE (level <= maxlevel) LOOP
INSERT INTO list_of_levels
SELECT level;
level = level + 1;
END LOOP;
select * from list_of_levels;
END;
$$ LANGUAGE PLPGSQL VOLATILE;
Then i try to call this function with: select get_levels_test (3), which shows me this error:
ERROR: query has no destination for result data
Hint: If you want to discard the results of a SELECT, use PERFORM instead.
Where: PL/pgSQL function "get_levels_test" line 12 at SQL statement
The list_of_levels table contains just an int column.
In case this is needed, I am using PostgreSQL 8.2.15 (Greenplum Database 4.3.3.1 build 1).
You need to use "return next" which can be used with a composite type or with a table. Please use this feature with caution as you can have performance issues with using this. Do not use this to join the results to another table. Do not return large datasets with this. Only use it for very small results such as a short report.
You also need to add exception handling into your function. I added this to my example function below.
Example table:
Example data:
Function:
And using the function: