Skip to content

Instantly share code, notes, and snippets.

@thesuhu
Created December 12, 2021 05:02
Show Gist options
  • Save thesuhu/df80a36e0fa368d29129e9d1609b5bc4 to your computer and use it in GitHub Desktop.
Save thesuhu/df80a36e0fa368d29129e9d1609b5bc4 to your computer and use it in GitHub Desktop.
Function to Get Digits from Strings in MySQL Version 8.0.3 or Below
DELIMITER $$
CREATE FUNCTION extract_digits (string_mixed VARCHAR(100)) RETURNS VARCHAR(100) NO SQL
BEGIN
DECLARE find_digit_position VARCHAR(100);
DECLARE string_digits VARCHAR(100) DEFAULT '';
DECLARE search_char VARCHAR(1);
DECLARE i INTEGER DEFAULT 1;
IF LENGTH(string_mixed) > 0 THEN
WHILE(i <= LENGTH(string_mixed)) DO
SET search_char = SUBSTRING(string_mixed, i, 1);
SET find_digit_position = FIND_IN_SET(search_char, '0,1,2,3,4,5,6,7,8,9');
IF find_digit_position > 0 THEN
SET string_digits = CONCAT(string_digits, search_char);
END IF;
SET i = i + 1;
END WHILE;
RETURN string_digits;
ELSE
RETURN '';
END IF;
END$$
DELIMITER ;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment