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?

asked Apr 22, 2018 at 15:01
2
  • Please provide a meaningful example. returns void and a syntactically incorrect SELECT don't make sense. And always your version of Postgres. I think there is a solution. Commented Apr 24, 2018 at 14:34
  • You could pass an array of a record type Commented Apr 24, 2018 at 14:58

2 Answers 2

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 ...

answered Apr 24, 2018 at 14:55
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.

answered Apr 22, 2018 at 15:05

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.