View Single Post

   
  #2 (permalink)  
Old 02-28-2008, 07:36 AM
bradsweb2@hotmail.com
 
Posts: n/a
Default Re: MySQL Function / Cursor Help

I found the problem with my SQL. I was trying to CALL a procedure
within a function, which is illegal in MySQL. My solution was to use my
split_string procedure with MySQL's FIND_IN_SET to come up with the
function below.

/* Returns true if an element is common to two comma-delimited sets of
numbers
* Precondition: set2 can't contain more than 64 elements (FIND_IN_SET
limitation)
*/
CREATE FUNCTION intersect ( set1 TEXT , set2 TEXT ) RETURNS INTEGER
BEGIN
DECLARE cur_position INT DEFAULT 1;
DECLARE remainder TEXT;
DECLARE cur_string VARCHAR(1000);

SET remainder = set1;
WHILE CHAR_LENGTH( remainder ) > 0 AND cur_position > 0 DO
SET cur_position = INSTR(remainder, ',');
IF cur_position = 0 THEN
SET cur_string = remainder;
ELSE
SET cur_string = LEFT(remainder, cur_position - 1);
END IF;
IF TRIM(cur_string) != '' AND FIND_IN_SET( cur_string, set2 )
THEN
RETURN TRUE;
END IF;
SET remainder = SUBSTRING(remainder, cur_position + 1);
END WHILE;
RETURN FALSE;
END

SELECT intersect( '1,2,3,4,5' , '4,5,6,7,8' ) /* returns true */
SELECT intersect( '1,2,3,4,5' , '6,7,8,9,0' ) /* returns false */

Reply With Quote