Обсуждение: Using a tablename as a parameter to a function.

Поиск
Список
Период
Сортировка

Using a tablename as a parameter to a function.

От
Stephen Ingram
Дата:

Hi there,

Is it possible (legal syntax, I mean) to pass a tablename
as a parameter to a function?

I don't know if its impossible or just that my plpgsql code is
not up to scratch.


Don't laugh, I'm just starting!  :)

Thanks for any pointers anyone can give.

steve


=======================================================================


drop function testfunc( text );

create function testfunc( text ) returns int
as
'
    declare
        rowcount          int         := 0;

        tablename         alias for $1;

    begin

        -- ----------------------------------------------------------
        -- Report on the number of entries in the table.
        -- ----------------------------------------------------------

        select into rowcount count(*) from tablename;

        return rowcount;

    end;
'
language 'plpgsql';

select testfunc( 'MyTable' );
select testfunc( 'ATable' );
select testfunc( 'BigTable' );

Re: Using a tablename as a parameter to a function.

От
Tom Lane
Дата:
Stephen Ingram <ingram@samsix.com> writes:
> Is it possible (legal syntax, I mean) to pass a tablename
> as a parameter to a function?

You could pass the tablename as a string argument (eg, text or varchar)
and then construct your queries as strings for plpgsql's EXECUTE
function.  This is notationally tedious, and you lose some performance
because there's no possibility to cache and reuse query plans, but
it will work.

            regards, tom lane