我是MySQL的新手,所以需要一些帮助。
我有一个表,其中有一个varchar列,其中包含逗号分隔字符串,如下所示:
cat_1,cat_2,cat_3,cat_4,cat_5
cat_6,cat_7,cat_8,cat_5
cat_1,cat_2,cat_5
cat_1,cat_2,cat_9,cat_4,cat_5
cat_7,cat_5我想要创建一个游标,我可以用它在这样一个字符串中循环每个cat_值。
我必须将每个子字符串与一个集合值进行比较,然后在此基础上执行一些逻辑。
在算法方面,这是我所需要的:
foreach row
foreach substring s in big_string
if s='cat_1'
--do logic
else if s='cat_2'
--do logic
else if s='cat_3'
--do logic
--and so on
end
end
end我知道如何使用普通的select游标创建外部循环。我只是不知道如何创建内部循环,它在每个逗号分隔的子字符串上循环。
有人能帮忙吗?
编辑:--我需要这个作为存储过程。
发布于 2013-10-18 00:28:01
首先,获取分隔字符串的第n段的函数:
DELIMITER $$
DROP FUNCTION IF EXISTS `string_splitter` $$
CREATE FUNCTION `string_splitter`(
str text,
delim varchar(255),
pos int) RETURNS text CHARSET utf8
BEGIN
return replace(substring_index(str, delim, pos), concat(substring_index(str, delim, pos - 1), delim), '');
END $$
DELIMITER ;现在是代码,它使用该函数来迭代分隔字符串的各个部分:
set @str = 'cat_1,cat_2,cat_3,cat_4,cat_5'; -- replace this with the value from the cursor
set @delim = ',';
set @numPieces = 1 + ((length(@str) - length(replace(@str, @delim, ''))) / length(@delim));
set @i = 1;
while @i <= @numPieces do
set @piece = string_splitter(@str, @delim, @i);
-- do something here with @piece
set @i = @i + 1;
end while;https://stackoverflow.com/questions/19334028
复制相似问题