Example: Counter

 

Suppose that you want to number the rows in a SELECT statement. So you write a user-defined function (UDF) that increments and returns a counter.

By using the code examples, you agree to the terms of the Code license and disclaimer information.

This example uses an external function with DB2® SQL parameter style and a scratchpad.

CREATE FUNCTION COUNTER()
       RETURNS INT        SCRATCHPAD        NOT DETERMINISTIC        NO SQL        NO EXTERNAL ACTION        LANGUAGE C        PARAMETER STYLE DB2SQL
       EXTERNAL NAME 'MYLIB/MATH(ctr)'
       DISALLOW PARALLEL

/* structure scr defines the passed scratchpad for the function "ctr" */
struct scr {
   long len;
   long countr;
   char not_used[92];
};

void ctr (
   long *out,                           /* output answer (counter) */
   short *outnull,                      /* output NULL indicator */
   char *sqlstate,                      /* SQL STATE */
   char *funcname,                      /* function name */
   char *specname,                      /* specific function name */
   char *mesgtext,                      /* message text insert */
   struct scr *scratchptr) {            /* scratch pad */

   *out = ++scratchptr->countr;      /* increment counter & copy out */
   *outnull = 0;
   return;
}
/* end of UDF : ctr */

For this UDF, observe that:

 

Parent topic:

Examples: UDF code