Extract numbers out of a string

Developed In: SQL — Contributed by: ushastry

Yesterday on EE I saw a very interesting request from a user for "Extracting numbers out of a string". This could be done in other languages with just 1 liner code but he needed it inside a SELECT query. http://www.experts-exchange.com/Programming/Languages/SQL_Syntax/Q_24855357.html

So I came with a very small MySQL function which was doing as needed by the user. I'm not sure whther this is the best way to do this but "There is always room for improvement."


ushastry
SQL
  1. DELIMITER $$
  2.  
  3.  
  4.  
  5. DROP FUNCTION IF EXISTS `uExtractNumberFromString`$$
  6. CREATE FUNCTION `uExtractNumberFromString`(in_string varchar(50)) RETURNS INT
  7. NO SQL
  8.  
  9.  
  10. BEGIN
  11.  
  12.  
  13. DECLARE ctrNumber varchar(50);
  14. DECLARE finNumber varchar(50) DEFAULT ' ';
  15. DECLARE sChar varchar(2);
  16. DECLARE inti INTEGER DEFAULT 1;
  17.  
  18.  
  19. IF length(in_string) > 0 THEN
  20.  
  21.  
  22. WHILE(inti <= length(in_string)) DO
  23. SET sChar= SUBSTRING(in_string,inti,1);
  24. SET ctrNumber= FIND_IN_SET(sChar,'0,1,2,3,4,5,6,7,8,9');
  25.  
  26.  
  27. IF ctrNumber > 0 THEN
  28.  
  29.  
  30. SET finNumber=CONCAT(finNumber,sChar);
  31. ELSE
  32.  
  33.  
  34. SET finNumber=CONCAT(finNumber,'');
  35. END IF;
  36.  
  37.  
  38. SET inti=inti+1;
  39. END WHILE;
  40. RETURN CAST(finNumber AS SIGNED INTEGER) ;
  41. ELSE
  42. RETURN 0;
  43. END IF;
  44.  
  45.  
  46. END$$
  47.  
  48.  
  49.  
  50. SELECT uExtractNumberFromString('12;e1hhsak123s12');
  51. 12112312
  52.  
  53.  
  54.  

You must be logged in to tag this tool

No Comments yet

Votes

Not yet rated.
You must be logged in to vote.

Watches

0 members are watching this tool
You must be logged in to track this tool.

Provide Feedback

Please note:
HTML will be purified, but we allow for a number of HTML tags so that you have the flexibility to decorate your comment text to some extent. The comments allow the following HTML tags:

strong, b, em, blockquote, a, code, pre

To put code into your comment, simply encapsulate your code with
[code language="XXX"][/code], where XXX is any common language, for instance "PHP", "SQL", "C", etc.



You must be logged in to comment