PREPARE dynamic SQL in plpgsql

Started by Koichi Suzukialmost 10 years ago3 messages
#1Koichi Suzuki
koichi.szk@gmail.com

Hi,

Does someone know how to prepare a synamic SQL statement in plpgsql?

All the examples, PG documents describe only about preparing static SQL
statement.

Thank you;
------
Koichi Suzuki

#2David G. Johnston
david.g.johnston@gmail.com
In reply to: Koichi Suzuki (#1)
Re: PREPARE dynamic SQL in plpgsql

On Fri, Mar 11, 2016 at 4:45 PM, Koichi Suzuki <koichi.szk@gmail.com> wrote:

Hi,

Does someone know how to prepare a synamic SQL statement in plpgsql?

All the examples, PG documents describe only about preparing static SQL
statement.

You might want to rephrase the question. From the pl/pgsql documentation:

"Note: The PL/pgSQL EXECUTE statement is not related to the EXECUTE SQL
statement supported by the PostgreSQL server. The server's EXECUTE
statement cannot be used directly within PL/pgSQL functions (and is not
needed)."

http://www.postgresql.org/docs/9.5/interactive/plpgsql-statements.html#PLPGSQL-STATEMENTS-EXECUTING-DYN

So even if you could SQL-PREPARE you wouldn't be able to execute it.

The linked section describes how to construct and execute dynamic queries
in pl/pgsql. The short answer is you create variable of type text and then
EXECUTE it.

stmt := format('SELECT * FROM %i', in_tbl_name);
EXECUTE stmt [...]

David J.

#3David G. Johnston
david.g.johnston@gmail.com
In reply to: Koichi Suzuki (#1)
Re: PREPARE dynamic SQL in plpgsql

On Fri, Mar 11, 2016 at 4:45 PM, Koichi Suzuki <koichi.szk@gmail.com> wrote:

Hi,

Does someone know how to prepare a synamic SQL statement in plpgsql?

All the examples, PG documents describe only about preparing static SQL
statement.

This is not an appropriate question for the -hackers list. It is better
asked on either -general or, more correctly, -novice.

It is also somewhat lacking in detail - including an example of what you've
tried or read would be a nice touch.

David J.