Re: PREPARE dynamic SQL in plpgsql

From: "David G(dot) Johnston" <david(dot)g(dot)johnston(at)gmail(dot)com>
To: Koichi Suzuki <koichi(dot)szk(at)gmail(dot)com>
Cc: PG Hackers <pgsql-hackers(at)postgresql(dot)org>
Subject: Re: PREPARE dynamic SQL in plpgsql
Date: 2016-03-11 23:55:03
Message-ID: CAKFQuwbEO8h7ivn2pFuSt9hwUmPjN7Mf+xub26UE+8UE7NxcHw@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

On Fri, Mar 11, 2016 at 4:45 PM, Koichi Suzuki <koichi(dot)szk(at)gmail(dot)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.

In response to

Browse pgsql-hackers by date

  From Date Subject
Next Message Tom Lane 2016-03-11 23:55:58 Re: Perl's newSViv() versus 64-bit ints?
Previous Message Jim Nasby 2016-03-11 23:50:10 Re: amcheck (B-Tree integrity checking tool)