From: Andreas Kretschmer <akretschmer@spamfence.net>
To: pgsql-sql@postgresql.org
Subject: Re: Table name as a variable in SELECT query
Date: Sat, 18 Dec 2010 15:01:04 +0100
Message-ID: <20101218140104.GA16363@tux> (raw)
In-Reply-To: <20101218074638.18205@web014.roc2.bluetie.com>
References: <20101218074638.18205@web014.roc2.bluetie.com>
Andrey Fokin <affox@myway.com> wrote:
> Hi,
> please advise is possible in SELECT query use variable as a table name?
>
> I would like to have for example something like:
>
> CREATE OR REPLACE FUNCTION test_name (tb varchar) RETURNS int AS $$
>
> DECLARE
>
> ......
>
> BEGIN
> SELECT * FROM $1;
> ........
>
> Will be grateful for any idea about.
Yes, it is possible, with dynamic sql. You have to build a string that
contains your query, and then execute (it's a command in pl/pgsql) that
string. Read more:
http://www.postgresql.org/docs/current/interactive/plpgsql-statements.html#PLPGSQL-STATEMENTS-EXECUT...
Andreas
--
Really, I'm not out to destroy Microsoft. That will just be a completely
unintentional side effect. (Linus Torvalds)
"If I was god, I would recompile penguin with --enable-fly." (unknown)
Kaufbach, Saxony, Germany, Europe. N 51.05082°, E 13.56889°
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Reply to all the recipients using the --to and --cc options:
reply via email
To: pgsql-sql@postgresql.org
Cc: akretschmer@spamfence.net
Subject: Re: Table name as a variable in SELECT query
In-Reply-To: <20101218140104.GA16363@tux>
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox