创建一个 num_char_extract.sql 文件内容如下,在 mysql shell 中使用 source 执行,这样就新建了一个函数。
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 BEGIN DECLARE len INT DEFAULT 0; DECLARE Tmp VARCHAR(100) DEFAULT ''; SET len=CHAR_LENGTH(Varstring); IF flag = 0 THEN WHILE len > 0 DO IF MID(Varstring,len,1)REGEXP'[0-9]' THEN SET Tmp=CONCAT(Tmp,MID(Varstring,len,1)); END IF; SET len = len - 1; END WHILE; ELSEIF flag=1 THEN WHILE len > 0 DO IF (MID(Varstring,len,1)REGEXP '[a-zA-Z]') THEN SET Tmp=CONCAT(Tmp,MID(Varstring,len,1)); END IF; SET len = len - 1; END WHILE; ELSEIF flag=2 THEN WHILE len > 0 DO IF ( (MID(Varstring,len,1)REGEXP'[0-9]') OR (MID(Varstring,len,1)REGEXP '[a-zA-Z]') ) THEN SET Tmp=CONCAT(Tmp,MID(Varstring,len,1)); END IF; SET len = len - 1; END WHILE; ELSEIF flag=3 THEN WHILE len > 0 DO IF NOT (MID(Varstring,len,1)REGEXP '^[u0391-uFFE5]') THEN SET Tmp=CONCAT(Tmp,MID(Varstring,len,1)); END IF; SET len = len - 1; END WHILE; ELSE SET Tmp = 'Error: The second paramter should be in (0,1,2,3)'; RETURN Tmp; END IF; RETURN REVERSE(Tmp); END$$ DELIMITER ;
mysql> source /tmp/tmpcode/num_char_extract.sql Query OK, 0 rows affected, 1 warning (0.00 sec) Query OK, 0 rows affected (0.15 sec)
测试效果
mysql> select num_char_extract("123中国ABC",0); +------------------------------------+ | num_char_extract("123中国ABC",0) | +------------------------------------+ | 123 | +------------------------------------+ 1 row in set (0.06 sec) mysql> select num_char_extract("123中国ABC",2); +------------------------------------+ | num_char_extract("123中国ABC",2) | +------------------------------------+ | 123ABC | +------------------------------------+ 1 row in set (0.00 sec) mysql> select num_char_extract("123中国ABC",3); +------------------------------------+ | num_char_extract("123中国ABC",3) | +------------------------------------+ | 中国 | +------------------------------------+ 1 row in set (0.00 sec) mysql> insert into t2(name) values("1500万人民币元"),("300美元"),("54648万人民币"),("855598万日元"); Query OK, 4 rows affected (0.14 sec) Records: 4 Duplicates: 0 Warnings: 0 mysql> select name from t2; +---------------------+ | name | +---------------------+ | 1500万人民币元 | | 300美元 | | 54648万人民币 | | 855598万日元 | +---------------------+ 4 rows in set (0.00 sec) mysql> select name,num_char_extract(name,3) from t2; +---------------------+--------------------------+ | name | num_char_extract(name,3) | +---------------------+--------------------------+ | 1500万人民币元 | 万人民币元 | | 300美元 | 美元 | | 54648万人民币 | 万人民币 | | 855598万日元 | 万日元 | +---------------------+--------------------------+ 4 rows in set (0.00 sec)
摘自:https://blog.csdn.net/weixin_39198406/article/details/83543648