I can’t find anything in the PostgreSQL documentation that shows how to declare a record, or row, while declaring the tuple structure at the same time. If you don’t define you tuple structure you get the error “The tuple structure of a not-yet-assigned record is indeterminate”.
This is what I’m doing now, which works fine, but there must be a better way to do it.
CREATE OR REPLACE FUNCTION my_func()
RETURNS TABLE (
"a" integer,
"b" varchar
) AS $$
DECLARE r record;
BEGIN
CREATE TEMP TABLE tmp_t (
"a" integer,
"b" varchar
);
-- Define the tuple structure of r by SELECTing an empty row into it.
-- Is there a more straight-forward way of doing this?
SELECT * INTO r
FROM tmp_t;
-- Now I can assign values to the record.
r.a := at.something FROM "another_table" at
WHERE at.some_id = 1;
-- A related question is - how do I return the single record 'r' from
-- this function?
-- This works:
RETURN QUERY
SELECT * FROM tmp_t;
-- But this doesn't:
RETURN r;
-- ERROR: RETURN cannot have a parameter in function returning set
END; $$ LANGUAGE plpgsql;
You are mixing the syntax for returning
SETOFvalues with syntax for returning a single row or value.When you declare a function with
RETURNS TABLE, you have to useRETURN NEXTin the body to return a row (or scalar value). And if you want to use arecordvariable with that it has to match the return type. Refer to the code examples further down.Return a single value or row
If you just want to return a single row, there is no need for a record of undefined type. @Kevin already demonstrated two ways. I’ll add a simplified version with
OUTparameters:You don’t even need to add
RETURN;in the function body, the value of the declaredOUTparameters will be returned automatically at the end of the function –NULLfor any parameter that has not been assigned.And you don’t need to declare
RETURNS RECORDbecause that’s already clear from theOUTparameters.Return a set of rows
If you actually want to return multiple rows (including the possibility for 0 or 1 row), you can define the return type as
RETURNS…SETOF some_type, wheresome_typecan be any registered scalar or composite type.TABLE (col1 type1, col2 type2)– an ad-hoc row type definition.SETOF recordplusOUTparameters to define column names andtypes.100% equivalent to
RETURNS TABLE.SETOF recordwithout further definition. But then the returned rows are undefined and you need to include a column definition list with every call (see example).The manual about the record type:
There is more, read the manual.
You can use a record variable without assigning a defined type, you can even return such undefined records:
Call:
But this is very unwieldy as you have to provide the column definition list with every call. It can generally be replaced with something more elegant:
RETURNS TABLEor friends).Refactor a PL/pgSQL function to return the output of various SELECT queries
Your question is unclear as to what you need exactly.