Re: EXECUTE 'EXECUTE ...' or how to use dynamic prepared statements ?

From: "Dirk Jagdmann" <jagdmann(at)gmail(dot)com>
To: "Marc Mamin" <M(dot)Mamin(at)intershop(dot)de>
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: EXECUTE 'EXECUTE ...' or how to use dynamic prepared statements ?
Date: 2007-09-04 09:38:29
Message-ID: 5d0f60990709040238i1bd78235md22663f8bd2f2700@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

Hello Marc,

at first I tried to solve your update of the tables. The example you
gave should be done with an update statement like the following:

update test_table
set mygroup=(select t.mygroup
from test_table as t
where t.family = test_table.family
and t.rang = test_table.rang+1)
where rang=0;

If you have to write a function which receives the tablename as an
argument it would look like:

CREATE OR REPLACE FUNCTION test_function(tablename text)
RETURNS integer AS $BODY$
BEGIN
EXECUTE 'update ' || tablename || '
set mygroup=(select t.mygroup
from ' || tablename || ' as t
where t.family = test_table.family
and t.rang = test_table.rang+1)
where rang=0;'
RETURN 0;
END;
$BODY$
LANGUAGE 'plpgsql' VOLATILE;

Generally you should avoid using explicit for/loop constructs in your
stored procedures if the action can be solved by a single SQL
statement, because the optimizer can make a better execution plan.

--
---> Dirk Jagdmann
----> http://cubic.org/~doj
-----> http://llg.cubic.org

In response to

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Aleksandr Vinokurov 2007-09-04 10:37:36 8.0.1 to 8.0.13 upgrade added 15% lack of time of query execution
Previous Message Bart Degryse 2007-09-04 09:03:43 Use of delete...returning in function problem