0

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

2 Answers 2

1

You missed END IF;

  WHILE idx <= LENGTH(phone) DO
    SET ch = MID(phone,idx,1);
    IF LOCATE(ch, digits) > 0 THEN SET clean = CONCAT(clean, ch);
    END IF;
    SET idx = idx + 1;
  END WHILE;
Sign up to request clarification or add additional context in comments.

Comments

0

You forget to close if block.

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 IF;
  END WHILE;
  RETURN clean;
END $$
DELIMITER ;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.