Example: String search

Suppose you have written a UDF to look for the existence of a given short string, passed as an argument, within a given CLOB value that is also passed as an argument. The UDF returns the position of the string within the CLOB if it finds the string, or zero if it does not.

The C program was written to return a FLOAT result. Suppose you know that when it is used in SQL, it should always return an INTEGER. You can create the following function:

     CREATE FUNCTION FINDSTRING (CLOB(500K), VARCHAR(200)) 
       RETURNS INTEGER 
       CAST FROM FLOAT 
       SPECIFIC FINDSTRING 
       EXTERNAL NAME 'MYLIB/MYPGM(FINDSTR)'
       LANGUAGE C 
       PARAMETER STYLE DB2SQL 
       NO SQL 
       DETERMINISTIC
       NO EXTERNAL ACTION 
       RETURNS NULL ON NULL INPUT

Note that a CAST FROM clause is used to specify that the UDF program really returns a FLOAT value, but you want to cast this to INTEGER before returning the value to the SQL statement which used the UDF. Also, you want to provide your own specific name for the function. Because the UDF was not written to handle NULL values, you use the RETURNS NULL ON NULL INPUT.