Re: tablename as function parameter

From: Jonathan Daugherty <cygnus(at)cprogrammer(dot)org>
To: pgsql-sql(at)postgresql(dot)org
Subject: Re: tablename as function parameter
Date: 2005-03-21 05:08:20
Message-ID: 20050321050820.GD20336@vulcan.cprogrammer.org
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

# I'm trying to create a function (language 'sql') with table name as
# single input parameter, but I always get syntax errors at
# "$1". Probably I am use wrong types.
#
# simple example:
#
# create function testfct (text) language sql as 'select count(*) from
# $1'

This doesn't work because the value of $1 isn't literally substituted
into the SQL function that you've created; it's treated as a value
token that can only be used in certain contexts.

If you want to select records from an arbitrary table, you can use the
table name parameter to build and execute a cursor in plpgsql. In my
experience, return values can't be quite so polymorphic without a lot
of pain and suffering but, then again, using SELECT * FROM $table
inside a function and expecting to return all of the results is
probably not something you'll need very often.

But here's a way, to be didactic:

CREATE OR REPLACE FUNCTION test(text) RETURNS SETOF record AS '
DECLARE
_table ALIAS FOR $1;
_mycursor refcursor;
_row record;
BEGIN
OPEN _mycursor FOR EXECUTE ''SELECT * FROM '' || _table;

FETCH _mycursor INTO _row;
WHILE FOUND LOOP
RETURN NEXT _row;
FETCH _mycursor INTO _row;
END LOOP;

RETURN;
END
' LANGUAGE plpgsql;

If you return SETOF RECORD, you'll need to be explicit about how the
return value is treated, depending on what you expect to get back from
the function:

mydb> SELECT * FROM test('mytable') AS (col1 integer, col2 text, col3
date);

--
Jonathan Daugherty
Command Prompt, Inc. - http://www.commandprompt.com/
PostgreSQL Replication & Support Services, (503) 667-4564

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Chandan_Kumaraiah 2005-03-21 07:08:05 equivalent of oracle rank() in postgres
Previous Message Jonathan Daugherty 2005-03-21 04:30:10 Re: Group by 15 Minute Steps