DELIMITER $$
DROP FUNCTION IF EXISTS `Num_char_extract`$$
CREATE FUNCTION `Num_char_extract`(Varstring VARCHAR(100)CHARSET utf8, flag INT) RETURNS VARCHAR(50) CHARSET utf8
COMMENT '标识 0 提取数字 1 提取字母 2提取数字+字母 3 提取汉字 4 提取汉字+数字+字母'
BEGINDECLARE len INT DEFAULT 0;DECLARE Tmp VARCHAR(100) DEFAULT '';SET len=CHAR_LENGTH(Varstring);IF flag = 0THENWHILE len > 0 DOIF MID(Varstring,len,1)REGEXP'[0-9]' THENSET Tmp=CONCAT(Tmp,MID(Varstring,len,1));END IF;SET len = len - 1;END WHILE;ELSEIF flag=1THENWHILE len > 0 DOIF (MID(Varstring,len,1)REGEXP '[a-zA-Z]')THENSET Tmp=CONCAT(Tmp,MID(Varstring,len,1));END IF;SET len = len - 1;END WHILE;ELSEIF flag=2THENWHILE len > 0 DOIF ( (MID(Varstring,len,1)REGEXP'[0-9]')OR (MID(Varstring,len,1)REGEXP '[a-zA-Z]') )THENSET Tmp=CONCAT(Tmp,MID(Varstring,len,1));END IF;SET len = len - 1;END WHILE;ELSEIF flag=3THENWHILE len > 0 DOIF NOT (MID(Varstring,len,1)REGEXP '^[u0391-uFFE5]')THENSET Tmp=CONCAT(Tmp,MID(Varstring,len,1));END IF;SET len = len - 1;END WHILE;ELSEIF flag=4THENWHILE len > 0 DOIF ( (MID(Varstring,len,1)REGEXP'[0-9]')OR (MID(Varstring,len,1)REGEXP '[a-zA-Z]')OR ((HEX(MID(Varstring,len,1)) REGEXP '^(..)*(E[4-9])' )))THENSET Tmp=CONCAT(Tmp,MID(Varstring,len,1));END IF;SET len = len - 1;END WHILE;ELSESET Tmp = 'Error: The second paramter should be in (0,1,2,3,4)';RETURN Tmp;END IF;RETURN REVERSE(Tmp);END$$
DELIMITER ;
检验:
SELECT Num_char_extract('哈112asdd****&,...,',1);
SELECT Num_char_extract('哈112asdd****&,...,',2);
SELECT Num_char_extract('哈112asdd****&,...,',3);
SELECT Num_char_extract('哈112asdd****&,...,',4);