mysql字符串分割
1、字符串分割函数
drop function if exists str_for_substr; CREATE DEFINER = `root`@`%` FUNCTION `str_for_substr`(`num` int, `str` varchar(5000)) RETURNS varchar(100) no sql BEGIN /*函数功能: 把带逗号的字符串分割取出 参数: num 要取出的字符串的索引值, 以0开始 str 以逗号分割的字符串 扩展: 将###替换成其他符合,即可完成不同分隔符拆分字符串,亦可以把分隔符作为参数 */ 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) ) + 4 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;
2、创建存储过程,循环插入截取的每一条数据
drop procedure if exists split_str; CREATE DEFINER = `root`@`%` PROCEDURE `split_str`() BEGIN DECLARE cnt int default 0; DECLARE num int default 0; DECLARE i int default 0; DECLARE j int default 0; declare str varchar(4000); # 统计当前截取字段表的数据量 select count(1) into cnt from test; # 循环查询每一条数据,此处可以换成游标处理 while i<= cnt do select query_knowledge_list_string into str from test limit i,1; # 查询每条数据###出现的次数 SET num = (LENGTH(str) - LENGTH(REPLACE(str, '###', ''))) / 3; while j <= num do # 循环插入截取后的数据 INSERT INTO test1 (knowledge_name, subject_name, grade_name) select str_for_substr(j,str), subjectName, grade_name from test limit i,1; set j = j + 1; end while; # 循环值归零 set j = 0; set i = i + 1; end while; END;
标签:INDEX,分割,CHAR,SUBSTRING,num,str,mysql,字符串,### From: https://www.cnblogs.com/zuouncle/p/16955246.html