Re: PLpgSQL FOR IN EXECUTE question

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: Christoph Haller <ch(at)rodos(dot)fzk(dot)de>
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: PLpgSQL FOR IN EXECUTE question
Date: 2002-11-07 18:01:31
Message-ID: 23283.1036692091@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

Christoph Haller <ch(at)rodos(dot)fzk(dot)de> writes:
> Consider the following PLpgSQL code fragment
> FOR this_record IN
> EXECUTE ''SELECT ''
> || quote_ident($1)
> || ''FROM ''
> || quote_ident($2)
> LOOP
> list := list || '', '' || this_record.$1 ;
> END LOOP;

> As expected, accessing a field via this_record.$1
> does not work.
> Can it be done otherwise?

FOR this_record IN
EXECUTE ''SELECT ''
|| quote_ident($1)
|| '' AS foo FROM ''
|| quote_ident($2)
LOOP
list := list || '', '' || this_record.foo ;
END LOOP;

There is still another gotcha here though: the datatype of foo had
better remain the same every time, else the cached query plan for
the concatenation will fail. Explicitly casting to text in the
EXECUTE'd SELECT might be a good idea:

EXECUTE ''SELECT CAST(''
|| quote_ident($1)
|| '' AS TEXT) AS foo FROM ''
|| quote_ident($2)

regards, tom lane

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Jeff Boes 2002-11-07 18:16:44 Quartile (etc) ranking in a SQL statement?
Previous Message Joe Conway 2002-11-07 17:25:37 Re: Generating a cross tab (pivot table)