I am trying to write a function for MySQL that will strip all non-digit characters from a submitted phone number. I keep getting a syntax error.
DELIMITER $$
CREATE FUNCTION cleanPhone(phone VARCHAR(20)) RETURNS VARCHAR(20)
DETERMINISTIC
BEGIN
DECLARE clean VARCHAR(20) DEFAULT '';
DECLARE idx TINYINT DEFAULT 1;
DECLARE ch CHAR(1);
DECLARE digits CHAR(10) DEFAULT '0123456789';
WHILE idx <= LENGTH(phone) DO
SET ch = MID(phone,idx,1);
IF LOCATE(ch, digits) > 0 THEN SET clean = CONCAT(clean, ch);
SET idx = idx + 1;
END WHILE;
RETURN clean;
END;
$$
DELIMITER ;
When I try to execute this code, I get the following error:
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '
WHILE; RETURN clean; END' at line 13