Example: Counting

Your simple counting function returns a 1 the first time and increments the result by one each time it is called. This function takes no SQL arguments, and by definition it is a NOT DETERMINISTIC function since its answer varies from call to call.

It uses the SCRATCHPAD to save the last value returned. Each time it is called, the function increments this value and returns it.

     CREATE FUNCTION COUNTER () 
       RETURNS INT 
       EXTERNAL NAME 'MYLIB/MYFUNCS(CTR)' 
       LANGUAGE C 
       PARAMETER STYLE DB2SQL 
       NO SQL 
       NOT DETERMINISTIC
       NOT FENCED 
       SCRATCHPAD 4
       DISALLOW PARALLEL

Note that no parameter definitions are provided, just empty parentheses. The above function specifies SCRATCHPAD and uses the default specification of NO FINAL CALL. In this case, the size of the scratchpad is set to only 4 bytes, which is sufficient for a counter. Since the COUNTER function requires that a single scratchpad be used to operate properly, DISALLOW PARALLEL is added to prevent DB2® from operating it in parallel.