SELECT multiple rows and columns into a record variable

Deadly 提交于 2020-01-04 12:22:40

问题


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;

回答1:


There are no table variables in plpgsql (at least up to v10).

You could use a temporary table:

  • Select from a table variable

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

  • Switching from FOR loops in plpgsql to set-based SQL commands

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

  • Window Functions or Common Table Expressions: count previous rows within range


来源:https://stackoverflow.com/questions/24949266/select-multiple-rows-and-columns-into-a-record-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!