Skip site navigation (1) Skip section navigation (2)

Re: Passing the table name as a function argument inPLPGSQL

From: Andreas Kretschmer <akretschmer(at)spamfence(dot)net>
To: pgsql-novice(at)postgresql(dot)org
Subject: Re: Passing the table name as a function argument inPLPGSQL
Date: 2011-06-14 13:43:35
Message-ID: 20110614134335.GA17684@tux (view raw or flat)
Thread:
Lists: pgsql-novice
Vincent Ficet <jean-vincent(dot)ficet(at)bull(dot)net> wrote:

> Hello,
> 
> 
> Is it possible to pass the name of the table to update to a given function ?
> 
> For example, how can I do something like:
> 
> CREATE FUNCTION compute_ipaddr(CHARACTER VARYING, INET)
>     AS $_$
> DECLARE
>    tbl_name ALIAS FOR $1;
>    module_ipaddr ALIAS FOR $2;
> BEGIN
>  UPDATE tbl_name SET ipaddr = module_ipaddr  ....
> 
> END;
> $_$
>     LANGUAGE PLPGSQL;
> 
> 
> Since this does not work, I have to do
> 
> IF tbl_name = 'controller' THEN
>   UPDATE controller SET ipaddr = module_ipaddr ...
> ELSE IF tbl_name = 'server' THEN
>   UPDATE server SET ipaddr = module_ipaddr ...
> [ ...]
> 
> 
> Is there a technique to pass the table name and so make the code more
> generic ?

Sure.

Build your SQL as an TEXT-String and EXECUTE them.


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

pgsql-novice by date

Next:From: l1Date: 2011-06-14 18:30:36
Subject: SERIAL order and INSERT order
Previous:From: Simon RiggsDate: 2011-06-14 09:36:29
Subject: Re: Scheduling autovacuum

Privacy Policy | About PostgreSQL
Copyright © 1996-2014 The PostgreSQL Global Development Group