1

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.

1 Answer 1

1

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;
Sign up to request clarification or add additional context in comments.

4 Comments

@hyman - CREATE FUNCTION my_concat(VARIADIC arr text[]) RETURNS text AS $$ SELECT array_to_string(arr, ''); $$ LANGUAGE SQL; Then call: select my_concat('hello', 'world', '.');
Thanks very much! your code is worked to handle numeric operations. but if i want to define a function like 'concat', what should i do? like this: select my_concat('hello', 'world', '.'); output: helloworld.
@Oto Shavadze Do you know how it works on GreenPlum? I have tried some ways but failed. CREATE FUNCTION my_concat(VARIADIC arr text[]) RETURNS text AS $$ SELECT array_to_string(arr, ''); $$ LANGUAGE SQL; ERROR: syntax error at or near "text" at character 40 LINE 1: CREATE FUNCTION my_concat(VARIADIC arr text[]) RETURNS text ... Thanks!
@hyman: If I paste your function into Postgres 9.5.5 it works as expected.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.