hyman
hyman

Reputation: 11

PostgreSQL - how to define a user-defined function with dynamic parameters?

As i know, when you create a user-defined function in postgresql, you must specify the parameters numbers and types. Like this:

CREATE OR REPLACE FUNCTION my_add(xx INTEGER, yy INTEGER) 
 RETURNS INTEGER AS 
 $$
   BEGIN
     RETURN xx + yy;
   END;
 $$ 
 LANGUAGE plpgsql;


select my_add(12, 34);
output: 46

Now i want to create a function which can receive dynamic parameters and works like this:

select my_add(1, 2);
output: 3

select my_add(1, 2, 3);
output: 6

select my_add(10, 4, 5, 1);
output: 20

Is there some ways to define dynamic parameters when you define your function ? How can i do that? thanks.

Upvotes: 1

Views: 223

Answers (1)

clemens
clemens

Reputation: 17722

You're searching for variadic parameters, e.g.:

CREATE FUNCTION mleast(VARIADIC arr numeric[]) RETURNS numeric AS $$
    SELECT min($1[i]) FROM generate_subscripts($1, 1) g(i);
$$ LANGUAGE SQL;

Upvotes: 1

Related Questions