MySQL REGEXP - Removing white space and non-numeric characters

前端 未结 4 1456
谎友^
谎友^ 2021-01-06 03:36

I want to do a search in a MySQL database for phone numbers.

At present with this query:

SELECT person FROM people WHERE phone_number RLIKE \'1234567         


        
4条回答
  •  隐瞒了意图╮
    2021-01-06 04:13

    i did a function that returns all numbers only.. then i called the function by

    SELECT person FROM people WHERE returnNumericOnly(phone_number) = '123456789'
    

    my function is like this:

    DELIMITER $$
    
    USE [tablename]$$
    
    DROP FUNCTION IF EXISTS `returnNumericOnly`$$
    
    CREATE DEFINER=`root`@`localhost` FUNCTION `returnNumericOnly`(str VARCHAR(1000)) RETURNS VARCHAR(1000) CHARSET latin1
    DETERMINISTIC
    BEGIN
      DECLARE counter INT DEFAULT 0;
      DECLARE strLength INT DEFAULT 0;
      DECLARE strChar VARCHAR(1000) DEFAULT '' ;
      DECLARE retVal VARCHAR(1000) DEFAULT '';
    
      SET strLength = LENGTH(str);
    
      WHILE strLength > 0 DO
        SET counter = counter+1;
        SET strChar = SUBSTRING(str,counter,1);
        IF strChar REGEXP('[0-9]+') = 1
          THEN SET retVal = CONCAT(retVal,strChar);
        END IF;
        SET strLength = strLength -1;
        SET strChar = NULL;
      END WHILE;
    RETURN retVal;
    END $$
    
    DELIMITER ;
    

提交回复
热议问题