在mysql中并没有split函数,需要自己写: 1)获得按指定字符分割的字符串的个数: Sql代码 DELIMITER$$ DROP FUNCTION IFEXISTS`sims`.`func_get_split_string_total`$$ CREATE DEFINER=`root`@`localhost` FUNCTION `func_get_split_string_total`( f_strin
在mysql中并没有split函数,需要自己写:
1)获得按指定字符分割的字符串的个数:
Sql代码
-
DELIMITER $$
-
-
DROP FUNCTION IF EXISTS `sims`.`func_get_split_string_total`$$
-
-
CREATE DEFINER=`root`@`localhost` FUNCTION `func_get_split_string_total`(
-
f_string varchar(1000),f_delimiter varchar(5)
-
) RETURNS int(11)
-
BEGIN
-
declare returnInt int(11);
-
if length(f_delimiter)=2 then
-
return 1+(length(f_string) - length(replace(f_string,f_delimiter,'')))/2;
-
else
-
return 1+(length(f_string) - length(replace(f_string,f_delimiter,'')));
-
end if;
-
END$$
-
-
DELIMITER ;
例:func_get_split_string_total('abc||def||gh','||') 结果为3
2)得到第i个分割后的字符串。
Sql代码
-
DELIMITER $$
-
-
DROP FUNCTION IF EXISTS `sims`.`func_get_split_string`$$
-
-
CREATE DEFINER=`root`@`localhost` FUNCTION `func_get_split_string`(
-
f_string varchar(1000),f_delimiter varchar(5),f_order int) RETURNS varchar(255) CHARSET utf8
-
BEGIN
-
declare result varchar(255) default '';
-
set result = reverse(substring_index(reverse(substring_index(f_string,f_delimiter,f_order)),f_delimiter,1));
-
return result;
-
END$$
-
-
DELIMITER ;
例如:func_get_split_string('abc||def||gh','||',2) 为def
3) 需求:A表中的一个字段值为1||2, 在select 时要通过和B字典表的关联得到a,b
Sql代码
-
CREATE DEFINER=`root`@`localhost` FUNCTION `getDictName`(v_str varchar(100)) RETURNS varchar(100) CHARSET utf8
-
BEGIN
-
-
DECLARE i int(4);
-
DECLARE dictCode varchar(100);
-
DECLARE dictName varchar(100);
-
DECLARE returnStr varchar(100);
-
-
set i = 1;
-
set returnStr = '';
-
-
if(v_str is null or length(v_str)=0) then
-
return returnStr;
-
else
-
-
while i'||')
-
do
-
set dictCode = func_get_split_string(v_str,'||',i);
-
-
select names into dictName from sims_dd_dict where code = dictCode;
-
-
set returnStr = concat(returnStr,',',dictName); -- 这里要用中文的逗号,否则导出EXCEL的时候会串行,因为程序中是以逗号分隔的
-
set i = i+1;
-
end while;
-
-
set returnStr = subString(returnStr,2);
-
return returnStr;
-
-
end if;
-
END$$
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn