write INSERT INTO temp_table1 SELECT get_some_data($1);
in place of what you had
select * into temp_table1 from get_some_data($1); -- error!
May be this will work for you.
Question
I've got a temp table which I want to use twice to insert into it:
CREATE OR REPLACE FUNCTION test1(user_id BIGINT) RETURNS BIGINT AS
$BODY$
BEGIN
DROP TABLE IF EXISTS temp_table1;
create temp table temp_table1
on commit drop
as select * from get_some_data($1); -- try to get the data for the 1st time
if not exists (select * temp_table1) then
select try_to_update_data($1); -- updates data, returns void
end if;
-- try to get the data again
select * into temp_table1 from get_some_data($1); -- error!
if not exists (select * from temp_table1) then
return 0;
end if;
--........ use temp_table1
It trows the error:
ERROR: "temp_table1" is not a known variable
How do I solve this?
Solution
write INSERT INTO temp_table1 SELECT get_some_data($1);
in place of what you had
select * into temp_table1 from get_some_data($1); -- error!
May be this will work for you.
OTHER TIPS
RowanStone is looking for a more detailed answer to this question.
The reason the SELECT INTO does not work is because there are two contexts to execute it and SELECT INTO TABLE
in not available in PL/pgSQL:
SELECT [ ALL | DISTINCT [ ON ( expression [, ...] ) ] ] * | expression [ [ AS ] output_name ] [, ...] INTO [ TEMPORARY | TEMP | UNLOGGED ] [ TABLE ] new_table
CREATE TABLE AS is functionally similar to SELECT INTO. CREATE TABLE AS is the recommended syntax, since this form of SELECT INTO is not available in ECPG or PL/pgSQL, because they interpret the INTO clause differently.
43.5.3. Executing a Command with a Single-Row Result
The result of an SQL command yielding a single row (possibly of multiple columns) can be assigned to a record variable, row-type variable, or list of scalar variables. This is done by writing the base SQL command and adding an INTO clause.
SELECT select_expressions INTO [STRICT] target FROM ...;
where target can be a record variable, a row variable, or a comma-separated list of simple variables and record/row fields.
Note that this interpretation of SELECT with INTO is quite different from PostgreSQL's regular SELECT INTO command, wherein the INTO target is a newly created table. If you want to create a table from a SELECT result inside a PL/pgSQL function, use the syntax CREATE TABLE ... AS SELECT.
Either INSERT INTO SELECT
should be used(append) or DROP TABLE
and CREATE TABLE AS SELECT ...
instead.