Search code examples
postgresqlplpgsqlpostgresql-9.3

SELECT multiple rows and columns into a record variable


In a plpgsql function, how can multiple rows and columns be selected into a record variable?

For example, I would like to SELECT multiple instances of two columns (yearinteger and value) into a record variable (yearvalues).

*EDIT - the following code is just part of a longer function, I need the variable yearvalues to contain multiple rows and columns from a table from which I can create further variables from

CREATE OR REPLACE FUNCTION fn_function ()
RETURNS TABLE () AS $$
DECLARE
    year c.year%TYPE;
    value c.value%TYPE;
    yearvalues record;
BEGIN
    FOR yearvalues IN 
    SELECT c.year, c.value FROM c
    LOOP
    END LOOP;
-- creation of additional variables from the yearvalues variable
END;
$$ LANGUAGE plpgsql;

Solution

  • There are no table variables in PL/pgSQL - at least up to Postgres 14, and likely never.

    Use temporary tables:

    Or substitute with CTEs (or just subqueries in simple cases) for the local scope of a single query. A "single query" can encompass multiple commands when using (data-modifying) CTEs. That would be most efficient:

    Or combine cursors with loops (consider the example under FNC - Function):

    But it's typically simpler and more efficient to use the implicit cursor of a FOR loop: