The FINAL function
The FINAL aggregate support function performs the post-iteration tasks for the user-defined aggregate.
The following table summarizes possible post-iteration tasks.
Post-iteration task | More information |
---|---|
Type conversion of the final state into the return type of the user-defined aggregate | Return an aggregate result different from the aggregate state |
Post-iteration calculations that the user-defined aggregate might need | Aggregate support functions that the algorithm requires |
Deallocation of memory that the INIT aggregate support function has allocated | Using a pointer-valued state for a UDA |
The FINAL function is an optional aggregate support function. If
your user-defined aggregate does not require one of the tasks in Table 1, you do not need to define a FINAL
function. When you omit the FINAL function from your user-defined
aggregate, the database server returns the final aggregate state as
the return value of the user-defined aggregate. If this state does
not match the expected data type of the aggregate return value, the
database server generates a data type mismatch error.
Important: In general, the FINAL support function must not deallocate
the aggregate state. Only for a pointer-valued state (in which the
aggregate support functions must handle all state management) does
the FINAL support function need to deallocate the state. For more
information, see Using a pointer-valued state for a UDA.
To declare a FINAL function as a C function, use the following
syntax:
agg_type final_func(final_state)
agg_state final_state;
- agg_type
- The data type of the aggregate result, which is what the user-defined aggregate returns to the SQL statement in which it was invoked.
- final_state
- The final aggregate state, as previous calls to the INIT and ITER functions have generated.
- final_func
- The name of the FINAL aggregate support function.
In the execution of a UDA, the database server calls the FINAL function after all iterations of the ITER function are complete.
The following code fragment shows the aggregate support functions
that handle an INTEGER argument for the SQSUM user-defined aggregate
(which Table 1 describes).
Figure 1. The FINAL aggregate
support function for SQSUM1 on INTEGER
/* SQSUM1 FINAL support function on INTEGER */
mi_integer final_sqsum1(state)
mi_integer state;
{
/* Calculate square of sum */
state *= state;
return (state);
}