I need to remove numbers from a name field in a SELECT query. The numbers are likely to be at the end of the string. Examples would be as follows:
Some Name
Namewithnospace
NamewithInt 100 <--- I want to remove this int from the string
I cannot guarantee that the first part of the string won’t contain a space, although I can be fairly sure that the number will be the last part of the string. Also most of the data won’t have a space.
I can see that there must be a solution using REVERSE() and SUBSTRING() but can’t work out how not to mangle the data that either has no spaces, or those that have a space but no integer.
edit: below is the definition for the MySQL C function that Ollie pointed me towards, with a change made by me to the regexp (to include spaces and punctuation in the function’s output):
DELIMITER !
DROP FUNCTION IF EXISTS alphas!
CREATE FUNCTION alphas ( str VARCHAR(255) )
RETURNS VARCHAR(255)
DETERMINISTIC
BEGIN
DECLARE i, len SMALLINT DEFAULT 1;
DECLARE ret VARCHAR(255) DEFAULT '';
DECLARE c VARCHAR(1);
SET len = CHAR_LENGTH( str );
REPEAT
BEGIN
SET c = MID( str, i, 1 );
IF c REGEXP '[[:alpha:]]' OR c REGEXP '[[:space:]]' THEN
SET ret=CONCAT(ret,c);
END IF;
SET i = i + 1;
END;
UNTIL i > len END REPEAT;
RETURN ret;
END !
DELIMITER ;
Make yourself this stored function called
alphas. It goes through the characters of its input text string one by one and removes all the digits.Then do this.
Here’s a useful resource from which I cribbed this function.
http://www.artfulsoftware.com/infotree/qrytip.php?id=815