Showing posts with label SQL. Show all posts

Friday, October 30, 2009

MySQL - Extract numbers out of a string

I recently came across a fascinating request on Experts Exchange where a user needed to extract numbers from a text string. While this is a simple one-liner in many programming languages, solving it directly inside a SQL SELECT query can be a bit tricky.
To help them out, I built a lightweight, custom MySQL function that gets the job done perfectly. While it works great, there is always room for improvement—so I'd love to hear how you would optimize it!


 
[code]  
DELIMITER $$

DROP FUNCTION IF EXISTS `uExtractNumberFromString`$$ 
CREATE FUNCTION `uExtractNumberFromString`(in_string varchar(50)) RETURNS INT NO SQL
BEGIN

DECLARE ctrNumber varchar(50);
DECLARE finNumber varchar(50) default ' ';
DECLARE sChar varchar(2);
DECLARE inti INTEGER default 1;

IF length(in_string) > 0 THEN
WHILE(inti <= length(in_string)) DO
    SET sChar= SUBSTRING(in_string,inti,1);
    SET ctrNumber= FIND_IN_SET(sChar,'0,1,2,3,4,5,6,7,8,9');

    IF ctrNumber > 0 THEN
       SET finNumber=CONCAT(finNumber,sChar);
    ELSE
       SET finNumber=CONCAT(finNumber,'');
    END IF;
    SET inti=inti+1;
END WHILE;
RETURN CAST(finNumber AS SIGNED INTEGER) ;
ELSE
  RETURN 0;
END IF;

END$$

[/code]

select uExtractNumberFromString('12;e1hhsak123s12');
12112312