数据库
首页 > 数据库> > mysql字符串分割函数(行转列)

mysql字符串分割函数(行转列)

作者:互联网

 

 

DELIMITER $$ 
CREATE DEFINER = `root`@`%` FUNCTION `str_for_substr`(`num` int, `str` varchar(5000))
  RETURNS varchar(100)
 BEGIN

 SET @str_for_substr =
   
  SUBSTRING(
         SUBSTRING_INDEX(str, ',', num + 1),
         CASE num
     WHEN 0 THEN
         CHAR_LENGTH(
             SUBSTRING_INDEX(str, ',', num)
         ) + 1
     ELSE
         CHAR_LENGTH(
             SUBSTRING_INDEX(str, ',', num)
         ) + 2
     END,
     CASE num
 WHEN 0 THEN
     CHAR_LENGTH(
         SUBSTRING_INDEX(str, ',', num + 1)
     ) - CHAR_LENGTH(
         SUBSTRING_INDEX(str, ',', num)
     )
 ELSE
     CHAR_LENGTH(
         SUBSTRING_INDEX(str, ',', num + 1)
     ) - CHAR_LENGTH(
         SUBSTRING_INDEX(str, ',', num)
     ) - 1
 END
 );
 
 
     RETURN @str_for_substr;
 END$$
DELIMITER ;

 

测试:

mysql> SELECT str_for_substr(3,'one,two,three,four,five,six,seven') as 'value';
+-------+
| value |
+-------+
| four |
+-------+
1 row in set

搜索

复制

<iframe></iframe>

标签:INDEX,SUBSTRING,转列,LENGTH,num,str,mysql,字符串,CHAR
来源: https://www.cnblogs.com/callbin/p/16415858.html