3

I would like to create a function that operates on a table, for example

create or replace function test(t table) 
    returns void language plpgsql as
$func$
begin   
    select * from t limit 10;
end;
$func$

Then, I can call the function with any tablename, e.g.

select test(myTable);

How would I do something like this?

spitfiredd
  • 151
  • 1
  • 2
  • 10

2 Answers2

5

You cannot declare a table as function parameter per se, since there are no table variables in Postgres. But there are various ways to achieve what you might want to achieve - which isn't exactly clear yet.

You can "pass" a table as ...

  1. ... table name (type text or name) - especially when tables may not actually exist (yet):

  2. ... object identifier (type regclass):

  3. ... row type of the table (type anyelement) using the concept of polymorphism:

Typically, you end up using dynamic SQL in the function. Be wary of SQL injection vectors. Related:

The return type depends on your input and what you want to achieve ...

Erwin Brandstetter
  • 185,527
  • 28
  • 463
  • 633
0

You can't really do something like that because every function must either

  • Be statically typed
  • Be declared with a table-alias specifying the types in the query.

So you'll either have to do..

CREATE FUNCTION test(t table) 
RETURNS composite-type
AS
  ...

Or,

SELECT *
FROM test(myTable) AS (x int, y int);

But at some point you have to state the types. Alternatively you can return a schema-less type, like jsonb.

Evan Carroll
  • 65,432
  • 50
  • 254
  • 507