Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select from a table variable

I am trying to save the result of a SELECT query, pass it, and reuse it in another PL/pgSQL function:

DECLARE
  table_holder my_table; --the type of table_holder is my_table;
  result text;

BEGIN
  SELECT * INTO table_holder FROM table_holder ;

  result = another_function(table_holder);  
  return result;
END

The code for another_function(table_holder my_table), respectively:

BEGIN

  RETURN QUERY
  SELECT col FROM table_holder where id = 1;

END

Is it possible to run a SELECT query on a variable? If not, is there a way to get around this limitation?

I am using PostgreSQL 9.2.

like image 340
Xin Avatar asked Jul 26 '13 05:07

Xin


People also ask

Can you SELECT into a table variable?

The question was it is possible to do SELECT INTO a Table Variable in T-SQL? The answer is it is not possible at all. Let us understand what we can do in a similar situation.

How do I SELECT a value from a table to a variable in SQL?

SELECT @local_variable is typically used to return a single value into the variable. However, when expression is the name of a column, it can return multiple values. If the SELECT statement returns more than one value, the variable is assigned the last value that is returned.

What is the use of SELECT * from table?

The * operator represents all the columns of a table. So, you don't need to specify each column name in the SELECT query to get data from all the columns. SELECT * FROM Employee; The above query returns all the rows and columns data from the Employee table, as shown below.


1 Answers

There are no "table variables" in plpgsql. That's something you would find in SQL Server.

Use a temporary table instead:

BEGIN

CREATE TEMP TABLE table_holder AS
SELECT * FROM table_holder
WHERE <some condition>
ORDER BY <some expression>
;

...

END

A temporary table exists for the lifetime of a session. To drop it at the end of the function (or an enclosing transaction) automatically, use ON COMMIT DROP in the creating statement.

CREATE TEMP TABLE table_holder ON COMMIT DROP AS
SELECT ...

The temporary table is visible in the same session, but not outside.

One alternative would be to use cursors in PL/pgSQL.

More alternatives:

  • SELECT multiple rows and columns into a record variable
like image 95
Erwin Brandstetter Avatar answered Oct 06 '22 16:10

Erwin Brandstetter