I am trying to turn select into function, but keep getting error: “query has no destination for result data”. Select returns 5 columns so I am trying to return table with 5 columns. I can not figure out what I am missing, please help!
CREATE OR REPLACE FUNCTION docs_getfunctionsindb() RETURNS TABLE( a name, b name, c text, d text, e text) AS $BODY$ begin SELECT n.nspname as "Schema", p.proname as "Name", pg_catalog.pg_get_function_result(p.oid) as "Returned data type", pg_catalog.pg_get_function_arguments(p.oid) as "Argument data types", CASE WHEN p.proisagg THEN 'agg' WHEN p.proiswindow THEN 'window' WHEN p.prorettype = 'pg_catalog.trigger'::pg_catalog.regtype THEN 'trigger' ELSE 'normal' END as "Type" FROM pg_catalog.pg_proc p LEFT JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace WHERE pg_catalog.pg_function_is_visible(p.oid) AND n.nspname <> 'pg_catalog' AND n.nspname <> 'information_schema' AND n.nspname = 'public' and p.proname != 'passgen' ORDER BY 1, 2, 4; end ; $BODY$ LANGUAGE plpgsql VOLATILE
Advertisement
Answer
As the error message suggests, you have to tell the function what to return. To return a table bases on a query use RETURN QUERY
, e.g.
CREATE OR REPLACE FUNCTION func() RETURNS TABLE(val int, txt text) LANGUAGE 'plpgsql' AS $$ BEGIN -- return columns match the columns declared in RETURNS TABLE RETURN QUERY SELECT 1,'txt'; END; $$;
And call it like this:
SELECT * FROM func(); val | txt -----+----- 1 | txt (1 row)
So, assuming your query is correct, the function should look like this:
CREATE OR REPLACE FUNCTION sip_docs_getfunctionsindb() RETURNS TABLE( a name, b name, c text, d text, e text) AS $BODY$ begin RETURN QUERY SELECT n.nspname as "Schema", p.proname as "Name", pg_catalog.pg_get_function_result(p.oid) as "Returned data type", pg_catalog.pg_get_function_arguments(p.oid) as "Argument data types", CASE WHEN p.proisagg THEN 'agg' WHEN p.proiswindow THEN 'window' WHEN p.prorettype = 'pg_catalog.trigger'::pg_catalog.regtype THEN 'trigger' ELSE 'normal' END as "Type" FROM pg_catalog.pg_proc p LEFT JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace WHERE pg_catalog.pg_function_is_visible(p.oid) AND n.nspname <> 'pg_catalog' AND n.nspname <> 'information_schema' AND n.nspname = 'public' and p.proname != 'passgen' ORDER BY 1, 2, 4; end ; $BODY$ LANGUAGE plpgsql VOLATILE