Database Reference
In-Depth Information
AS $$
DECLARE retval integer;
BEGIN
SELECT $1 + $2 +$3 INTO retval;
RETURN retval;
END;
$$ LANGUAGE plpgsql;
We just invoked a concept called function overloading. This feature allows us to de-
clare a function of the same name but with different parameters that potentially be-
have differently. This difference can be as subtle as just changing the data type of
one of the arguments to the function. The function that PostgreSQL invokes depends
on the closest match to the function arguments and expected return type.
But suppose we want to add together any number of integers? Well, PostgreSQL
has a way to do that also.
CREATE OR REPLACE FUNCTION addition (VARIADIC
arr integer[]) RETURNS integer
AS $$
DECLARE retval integer;
BEGIN
SELECT sum($1[i]) INTO retval FROM
generate_subscripts($1, 1) g(i) ;
RETURN retval;
END;
$$
LANGUAGE plpgsql;
This will allow us to pass in any number of integers, and get an appropriate re-
sponse. These functions of course do not handle real or numeric data types. To
handle other data types, simply declare the function again with those types, and call
them with the appropriate parameters.
For more information about variable parameters, see http://www.postgresql.org/
docs/9.2/static/xfunc-sql.html#XFUNC-SQL-VARIADIC-FUNCTIONS .
Search WWH ::




Custom Search