-- 1
CREATE FUNCTION `idToChar`(`str` INT) RETURNS varchar(10) CHARSET utf8
COMMENT '根据数字获取对应字母--26位数字内单个字母匹配'
BEGIN
DECLARE str1 VARCHAR(25) DEFAULT '';
DECLARE i INT DEFAULT 1;
CASE str
WHEN '0' THEN SET str1 ="";
WHEN '1' THEN SET str1 ="A";
WHEN '2' THEN SET str1 ="B";
WHEN '3' THEN SET str1 ="C";
WHEN '4' THEN SET str1 ="D";
WHEN '5' THEN SET str1 ="E";
WHEN '6' THEN SET str1 ="F";
WHEN '7' THEN SET str1 ="G";
WHEN '8' THEN SET str1 ="H";
WHEN '9' THEN SET str1 ="I";
WHEN '10' THEN SET str1 ="J";
WHEN '11' THEN SET str1 ="K";
WHEN '12' THEN SET str1 ="L";
WHEN '13' THEN SET str1 ="M";
WHEN '14' THEN SET str1 ="N";
WHEN '15' THEN SET str1 ="O";
WHEN '16' THEN SET str1 ="P";
WHEN '17' THEN SET str1 ="Q";
WHEN '18' THEN SET str1 ="R";
WHEN '19' THEN SET str1 ="S";
WHEN '20' THEN SET str1 ="T";
WHEN '21' THEN SET str1 ="U";
WHEN '22' THEN SET str1 ="V";
WHEN '23' THEN SET str1 ="W";
WHEN '24' THEN SET str1 ="X";
WHEN '25' THEN SET str1 ="Y";
WHEN '26' THEN SET str1 ="Z";
ELSE SET str1 = str;
END CASE;
RETURN str1;
END
-- -----------------------------------------------------------------------------------------------------
-- 2
CREATE FUNCTION `spiltNumber`(`str` VARCHAR(255)) RETURNS varchar(10) CHARSET utf8
COMMENT '字符串切割遍历示例 -- 遍历数字类型数组获取对应字母'
BEGIN
DECLARE str1 VARCHAR(255) DEFAULT '';
DECLARE number VARCHAR(255) DEFAULT '';
DECLARE count int DEFAULT 1;
-- 获取分割符数量 char_length不管汉字字母数字都按一个字符统计
SELECT CHAR_LENGTH(str) - CHAR_LENGTH(REPLACE(str,',','')) + 1 INTO count;
SET @i = 1;
-- 根据分割符遍历
WHILE @i <= count DO
-- 获取切割遍历字符串
SET number = SUBSTRING_INDEX(subString_index(str,',',@i),',',-1);
-- 校验不为空,纯数字,小于等于26
IF number <> '' and (number REGEXP '[^0-9]') < 1 and 26 >= number
THEN
-- 获取数字对应字母,进行拼接
SET str1 = CONCAT(str1 , idToChar(number));
END IF;
SET @i = @i + 1;
END WHILE;
RETURN str1;
END
执行结果:
SELECT spiltNumber('3,19,4,14');
-- CSDN
如果需要显示切割的每个字符串可以修改spiltNumber创建临时表储存展示,这只是根据一些网友的的方法整理一点方法,如果有更好的方法希望指点,谢谢