I’m trying to create a function which references a temporary table in PostgreSQL 8.4. Based on my research it seems the best way to do this is to use the EXECUTE command to execute my query from a defined string.
Unfortunately I’m getting an odd syntax error when trying to create the function.
My current function definition is as follows:
CREATE OR REPLACE FUNCTION example() RETURNS void AS $$
EXECUTE 'INSERT INTO table1 (col1, col2, col3) SELECT col1, col2, col3 from temp_table';
$$ LANGUAGE SQL;
The error I am getting is:
ERROR: syntax error at or near "'INSERT INTO table1 (col1, col2, col3) SELECT col1, col2, col3 from temp_table'"
LINE 2: execute 'INSERT INTO table1 (col1, col2, col3) SELECT col1...
It seems I get the same error regardless of what is actually in the string literal.
My questions are, 1) what is the correct syntax for using the EXECUTE feature, and 2) is there a better way to write a function like this that references a temporary table?
I think your problem is the language you’re using. EXECUTE in the SQL language:
isn’t the same as EXECUTE in PL/pgSQL:
You’re using the SQL EXECUTE (which executes a prepared statement) when you want to be using the PL/pgSQL EXECUTE (which executes a string as SQL).
Try this:
Or, another example that seems closer to what you seem to be trying to do:
That will insert
'pancakes'into the table that you pass in thetnameargument to the function.