postgres doesn't recognize temp table in function

跟風遠走 提交于 2019-11-30 22:55:41

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

The entire body of a SQL function is parsed before any of it is executed. While a SQL function can contain commands that alter the system catalogs (e.g., CREATE TABLE), the effects of such commands will not be visible during parse analysis of later commands in the function. Thus, for example, CREATE TABLE foo (...); INSERT INTO foo VALUES(...); will not work as desired if packaged up into a single SQL function, since foo won't exist yet when the INSERT command is parsed. It's recommended to use PL/pgSQL instead of a SQL function in this type of situation.

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 ...

OcRob

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 ;

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!