Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
like image 845
interpost Avatar asked Jul 25 '14 06:07

interpost


People also ask

How do I select multiple row values in SQL?

You may use the IN, ANY, or ALL operator in outer query to handle a subquery that returns multiple rows. Contents: Using IN operator with a Multiple Row Subquery. Using NOT IN operator with a Multiple Row Subquery.

How do I display multiple rows in one record in SQL?

You can concatenate rows into single string using COALESCE method. This COALESCE method can be used in SQL Server version 2008 and higher. All you have to do is, declare a varchar variable and inside the coalesce, concat the variable with comma and the column, then assign the COALESCE to the variable.

How do I select multiple rows in a DataFrame in R?

By using bracket notation on R DataFrame (data.name) we can select rows by column value, by index, by name, by condition e.t.c. You can also use the R base function subset() to get the same results. Besides these, R also provides another function dplyr::filter() to get the rows from the DataFrame.


1 Answers

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

Use temporary tables:

  • Select from a table variable

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:

  • 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

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

  • Postgres FOR LOOP
  • Cursor based records in PostgreSQL
like image 72
Erwin Brandstetter Avatar answered Oct 27 '22 21:10

Erwin Brandstetter