Search the MySQL manual:

12.2.2.2 UDF Calling Sequences for aggregate functions

Here follows a description of the different functions you need to define when you want to create an aggregate UDF function.

char *xxx_reset(UDF_INIT *initid, UDF_ARGS *args,
                char *is_null, char *error);

This function is called when MySQL finds the first row in a new group. In the function you should reset any internal summary variables and then set the given argument as the first argument in the group.

In many cases this is implemented internally by reseting all variables and then calling xxx_add().

char *xxx_add(UDF_INIT *initid, UDF_ARGS *args,
              char *is_null, char *error);

This function is called for all rows that belongs to the same group, except for the first row. In this you should add the value in UDF_ARGS to your internal summary variable.

The xxx() function should be declared identical as when you define a simple UDF function. See section 12.2.2.1 UDF Calling Sequences for simple functions.

This function is called when all rows in the group has been processed. You should normally never access the args variable here but return your value based on your internal summary variables.

All argument processing in xxx_reset() and xxx_add() should be done identically as for normal UDFs. See section 12.2.2.3 Argument Processing.

The return value handling in xxx() should be done identically as for a normal UDF. See section 12.2.2.4 Return Values and Error Handling.

The pointer argument to is_null and error is the same for all calls to xxx_reset(), xxx_add() and xxx(). You can use this to remember that you got an error or if the xxx() function should return NULL. Note that you should not store a string into *error! This is just a 1 byte flag!

is_null is reset for each group (before calling xxx_reset(). error is never reset.

If isnull or error are set after xxx() then MySQL will return NULL as the result for the group function.

User Comments

Add your own comment.