I have a Postgres function which is returning a table:
CREATE OR REPLACE FUNCTION testFunction() RETURNS TABLE(a int, b int) AS
$BODY$
DECLARE a int DEFAULT 0;
DECLARE b int DEFAULT 0;
BEGIN
CREATE TABLE tempTable AS SELECT a, b;
RETURN QUERY SELECT * FROM tempTable;
DROP TABLE tempTable;
END;
$BODY$
LANGUAGE plpgsql;
This function is not returning data in row and column form. Instead it returns data as:
(0,0)
That is causing a problem in Coldfusion cfquery block in extracting data. How do I get data in rows and columns when a table is returned from this function? In other words: Why does the PL/pgSQL function not return data as columns?
Of course you can do this by putting the function call in the
FROM
clause, like Eric Brandstetter correctly answered. However, this is sometimes complicating in a query that already has other things in the FROM clause. To get the individual columns that the function returns, you can use this syntax:Or to get only the column called "a":
Place the whole function, including the input value(s) in parenteses, followed by a dot and the desired column name, or an asterisk.
To get the column names that the function returns, you'll have to either:
SELECT * FROM testfunction()
.The input values can still come out of a
FROM
clause. Just to illustrate this, consider this function and test data:You could call the function "funky(a,b)", without the need to put it in the
FROM
clause:Which would result in 2 columns:
To get individual columns instead of the row type, call the function with:
Just like you would select all columns from a table.
Also consider this reviewed form of your test function:
In particular:
DECLARE
key word is only needed once.OUT
parameters in theRETURNS TABLE (...)
clause.The temporary table is completely useless in the example (probably over-simplified). You could reduce to: