Re: Table name as a variable in SELECT query

From: Andreas Kretschmer <akretschmer(at)spamfence(dot)net>
To: pgsql-sql(at)postgresql(dot)org
Subject: Re: Table name as a variable in SELECT query
Date: 2010-12-18 14:01:04
Message-ID: 20101218140104.GA16363@tux
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

Andrey Fokin <affox(at)myway(dot)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-EXECUTING-DYN

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°

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Николай Ижиков 2010-12-21 08:31:12 linux. ossp-uuid
Previous Message Andrey Fokin 2010-12-18 12:46:38 Table name as a variable in SELECT query