Database Reference
In-Depth Information
And we are done, as returning the sum (or NULL in case all elements were NULL
values) is exactly the same as in our previous function.
While this is all from the C side, we still need to teach PostgreSQL about this new
function. The simplest way is to declare a function which takes an int[] argument.
CREATE OR REPLACE FUNCTION add_arr(int[])
RETURNS int
AS '$libdir/add_func', 'add_int32_array'
LANGUAGE C STRICT;
It works fine for any integer array you pass it for:
hannu=# select add_arr('{1,2,3,4,5,6,7,8,9}');
-[ RECORD 1 ]
add_arr | 45
hannu=# select add_arr(ARRAY[1,2,NULL]);
-[ RECORD 1 ]
add_arr | 3
hannu=# select add_arr(ARRAY[NULL::int]);
-[ RECORD 1 ]
add_arr |
It even detects multidimensional arrays, and errors out if it is passed one: hannu=#
select add_arr('{{1,2,3},{4,5,6}}');
ERROR: 1-dimensional array needed
What if we want to use it the same way as our two-argument add(a,b) function ?
Since Version 8.4 of PostgreSQL, it is possible using support for VARIADIC func-
tions, or functions taking a variable number of arguments.
Create the function as follows:
Search WWH ::




Custom Search