How to only select numeric data from mysql?

后端 未结 6 1099
一个人的身影
一个人的身影 2020-11-30 12:09

Does mysql have a function like is_num() which can allow me determine the data is numeric or not?

6条回答
  •  粉色の甜心
    2020-11-30 12:36

    If you want to select only the numeric characters from your string, try using this:

    CREATE FUNCTION IsNumeric (val varchar(255)) RETURNS tinyint 
     RETURN val REGEXP '^(-|\\+){0,1}([0-9]+\\.[0-9]*|[0-9]*\\.[0-9]+|[0-9]+)$';
    
    CREATE FUNCTION NumericOnly (val VARCHAR(255)) 
     RETURNS VARCHAR(255)
    BEGIN
     DECLARE idx INT DEFAULT 0;
     IF ISNULL(val) THEN RETURN NULL; END IF;
    
     IF LENGTH(val) = 0 THEN RETURN ""; END IF;
    
     SET idx = LENGTH(val);
      WHILE idx > 0 DO
      IF IsNumeric(SUBSTRING(val,idx,1)) = 0 THEN
       SET val = REPLACE(val,SUBSTRING(val,idx,1),"");
       SET idx = LENGTH(val)+1;
      END IF;
      SET idx = idx - 1;
      END WHILE;
      RETURN val;
     END;
    

    Use it by calling the NumericOnly function like this:

    select NumericOnly('1&2') as result;
    

    Returns: "12"

    select NumericOnly('abc987') as result;
    

    Returns: "987"

    (BTW, I wrote a post about this here)

提交回复
热议问题