Re: EXECUTE USING problem

From: Raymond O'Donnell <rod(at)iol(dot)ie>
To: Graham <graham(at)gpmd(dot)co(dot)uk>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: EXECUTE USING problem
Date: 2011-11-15 13:26:47
Message-ID: 4EC26897.5070506@iol.ie
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On 15/11/2011 12:45, Graham wrote:
> Using PG 9.0.3, I wish to dynamically reference a column in a table
> passed into a PL/PgSQL function as follows:
>
> -- A table with some values.
> DROP TABLE IF EXISTS table1;
> CREATE TABLE table1 (
> code INT,
> descr TEXT
> );
>
> INSERT INTO table1 VALUES ('1','a');
> INSERT INTO table1 VALUES ('2','b');
>
> -- The function code.
> DROP FUNCTION IF EXISTS foo (TEXT);
> CREATE FUNCTION foo (tbl_name TEXT) RETURNS VOID
>
> AS $$
> DECLARE
> r RECORD;
> d TEXT;
> BEGIN
> FOR r IN
> EXECUTE 'SELECT * FROM ' || tbl_name
> LOOP
> --SELECT r.descr INTO d; --IT WORK
> EXECUTE 'SELECT ($1)' || '.descr' INTO d USING r; --DOES NOT WORK
> RAISE NOTICE '%', d;
> END LOOP;

I think that everything after EXECUTE needs to be a string. Also, USING
is part of an ORDER BY clause; so you'd do:

EXECUTE 'SELECT ($1)' || '.descr INTO d ORDER BY whatever USING
some_operator';

Ray.

--
Raymond O'Donnell :: Galway :: Ireland
rod(at)iol(dot)ie

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Tarlika Elisabeth Schmitz 2011-11-15 16:00:07 Re: all non-PK columns from information schema
Previous Message Pavel Stehule 2011-11-15 13:18:57 Re: EXECUTE USING problem