0

I am extracting data from a table using execute query. now I want to store this data in some variable to use it for other operation, and I cannot use temp table so I have to use WITH query.

--Something like this:

with ttable (col1, col2) as (execute 'select tcol1, tcol2 from tab_sample')
insert into tab_sam2 select col1,col2 from ttable;

Now this gives me error at execute saying syntax error at or near execute.

How can I do that. Also, Is there any alternate to store multiple data coming from a table in a procedure/function without using array or temp table?

Vishal D
  • 51
  • 9
  • `EXECUTE 'SELECT blah FROM ...' INTO your_var;` You don't need a CTE for this. In fact, unless you're using a dynamic statement, you don't need execute - just do `SELECT blah INTO your_var FROM ...` – 404 May 03 '18 at 16:22

1 Answers1

1

EXECUTE is a PL/pgSQL statement and cannot be mixed into SQL.

Why don't you do it like this:

EXECUTE E'WITH ttable (col1, col2) as (\n'
         '      SELECT tcol1, tcol2 FROM tab_sample\n'
         '   )\n'
         'INSERT INTO tab_sam2\n'
         '   SELECT col1,col2 FROM ttable';
Laurenz Albe
  • 209,280
  • 17
  • 206
  • 263