This could be because i'm tired, or that I'm new to postgres. However, I'm trying to use a temp table in a function and postgres is complaining that the "relation does not exist". Yet, if I take the body of my function, and execute it it works just fine. Below is a sample of the type of function I'm trying to create. Keeping in mind I've stripped out everything interesting such that it's close to a bare minimum to show my problem.
CREATE OR REPLACE FUNCTION dbo.somefunc() RETURNS void AS
$BODY$
CREATE TEMPORARY TABLE work_list
(
name text,
level smallint
);
insert into work_list
(name, level)
values
('someone', 25);
$BODY$
LANGUAGE sql VOLATILE;
The complaint I get is on the insert statement. The actual complaint is:
ERROR: relation "work_list" does not exist
Does postgres not support temp tables in functions? Or is there some syntax thing that I'm missing that the thing is choking on and it's giving me a bogus error?
combine the two statements. Create the temp table by doing a "select into" type syntax. In that way you can do it.
CREATE TEMP TABLE SomeTable AS SELECT * FROM OtherTable ;
Postgres runs some simple checks on the function you are trying to create, and it finds (correctly) that the table
work_list
does not (yet) exist. I see two options:1. "Fake it till you make it"
Actually create the (temporary) table before you create the function. The temporary table will be gone at the end of the session, but once the function is created, you have passed this test for good.Obviously, you'd have to drop that table before you run the function in the same session to avoid a conflict. Better, though: use
CREATE TEMP TABLE IF NOT EXISTS
in your function (Postgres 9.1+). You may want to truncate the table if it already exists ...However (see comments below), quoting the manual
Bold emphasis mine.
2. Use PL/pgSQL instead
Checks are less thorough in plpgsql. If Postgres still complains (which it doesn't in this case), you can also execute SQL dynamically with
EXECUTE
.Aside: In many cases, there is a more performant solution without temp table around the corner ...