DB2 User Defined Function (UDF)
Thursday, April 19th, 2007DB2 functions allow you to extend the functionality of database. Functions can be either database provided like SUM, AVG, COUNT, VALUE, etc whereas the other type is User Defined Function (UDF).
User defined function allows you to define your own features which normally cannot be provided by inbuild database functions.
Example - EXISTIN
This is the function that helps to check occurrence of string in CSV of string. Here’s the source -
-- Returns 0 if match found, else returns 1
CREATE FUNCTION schema.EXISTSIN
(VALUELST VARCHAR(1000), -- CSV String
VALUE VARCHAR(255), -- match to be found
DEL CHAR(1)) -- delimeter used in CSV stringRETURNS INTEGER
LANGUAGE SQL
BEGIN ATOMIC
DECLARE V_INDEX INTEGER ;
DECLARE V_RET INTEGER;
DECLARE V_TEMP VARCHAR(255);
DECLARE V_TEMP_LIST VARCHAR(1000);SET V_TEMP_LIST = SUBSTR( VALUELST, 1 );
WHILE( LENGTH( V_TEMP_LIST ) > 0 )
DO
SET V_INDEX = POSSTR(V_TEMP_LIST , ‘,’);
SET V_TEMP = SUBSTR(V_TEMP_LIST , 1, V_INDEX-1);
IF( V_TEMP = VALUE ) THEN
RETURN 0;
END IF;
SET V_TEMP_LIST = SUBSTR( V_TEMP_LIST, V_INDEX + 1 );
END WHILE;RETURN 1;
END
NOTE: though we did create this function, but later we realized there is function available in DB2 UDB 8.2 that does the same job. But may be, if other database don’t provide you with a function to do such job, then you can always write special user defined function to implement this.
SELECT * FROM MYTABLE WHERE LOCATE( COL1, 'ROHITBLOG,ROHITREVIEW' );
If there the column COL1 contains values ‘ROHITBLOG’, then it’ll return position of the match i.e. here it’s 1. The drawback here is if the value is ‘ROHIT’, then also it’ll return match and return non-zero value. So it would be safe to use existin function which breaks the CSV string and does exact match.