先設置:SET GLOBAL log_bin_trust_function_creators = 1;
1. 函數func_splitStringTotal:將字符串按指定方式分割,並計算單元總數 復制代碼 代碼如下:
DELIMITER $$
CREATE FUNCTION `func_get_splitStringTotal`(
f_string varchar(10000),f_delimiter varchar(50)
) RETURNS int(11)
BEGIN
return 1+(length(f_string) - length(replace(f_string,f_delimiter,'')));
END$$
DELIMITER ;
2.函數func_splitString:將字符串按指定方式分割,獲取指定位置的數
復制代碼 代碼如下:
DELIMITER $$
DROP function IF EXISTS `func_splitString` $$
CREATE FUNCTION `func_splitString`
( 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$$
SELECT func_splitString('1,2,3,4,5,6,7',',',1);
3.過程splitString 將字符串分割,並放到臨時表tmp_split 裡面
復制代碼 代碼如下:
DELIMITER $$
DROP PROCEDURE IF EXISTS `splitString` $$
CREATE PROCEDURE `splitString`
(IN f_string varchar(1000),IN f_delimiter varchar(5))
BEGIN
declare cnt int default 0;
declare i int default 0;
set cnt = func_split_TotalLength(f_string,f_delimiter);
DROP TABLE IF EXISTS `tmp_split`;
create temporary table `tmp_split` (`val_` varchar(128) not null) DEFAULT CHARSET=utf8;
while i < cnt
do
set i = i + 1;
insert into tmp_split(`val_`) values (func_split(f_string,f_delimiter,i));
end while;
END$$
call splitString('a,s,d,f,g,h,j',',');
SELECT * from tmp_split;