【原理】:
//f
SELECT SUBSTRING_INDEX('a,b,c,d,e,f',',',-1) ; -- f != 'a,b,c,d,e,f'
//e
SELECT SUBSTRING_INDEX('a,b,c,d,e,f',',',-2) ; -- e,f != 'a,b,c,d,e,f'
SELECT SUBSTRING_INDEX('e,f',',',1) ;
//d
SELECT SUBSTRING_INDEX('a,b,c,d,e,f',',',-3) ; -- d,e,f != 'a,b,c,d,e,f'
SELECT SUBSTRING_INDEX('d,e,f',',',1) ;
//c
SELECT SUBSTRING_INDEX('a,b,c,d,e,f',',',-4) ; -- c,d,e,f != 'a,b,c,d,e,f'
SELECT SUBSTRING_INDEX('c,d,e,f',',',1) ;
//b
SELECT SUBSTRING_INDEX('a,b,c,d,e,f',',',-5) ; -- b,c,d,e,f != 'a,b,c,d,e,f'
SELECT SUBSTRING_INDEX('b,c,d,e,f',',',1) ;
//a
SELECT SUBSTRING_INDEX('a,b,c,d,e,f',',',-6) ; -- a,b,c,d,e,f != 'a,b,c,d,e,f' OK
SELECT SUBSTRING_INDEX('a,b,c,d,e,f',',',1) ;
【实例】:
//变量声明 pnames = 'a,b,c,d,e,f'
DECLARE _z_end int DEFAULT 0;
DECLARE _z_num int DEFAULT -1;
DECLARE _z_str varchar(50);
set _name:= SUBSTRING_INDEX(pnames,',',1) ; -- _name 拆分后的值
while(_z_end <> -1) do
-- 字符拆分
set _z_str := SUBSTRING_INDEX(pnames,',',_z_num);
set _z_num = -1 + _z_num;
if(_z_str == pnames) then
_z_end := -1;
end if;
set _name:= SUBSTRING_INDEX(_z_str,',',1) ;
end while;
【运用】:
CREATE PROCEDURE `p_test`(IN `pnames` varchar(50))
BEGIN
-- pnames = 'a,b,c,d,e,f'
DECLARE _z_end int DEFAULT 0;
DECLARE _z_num int DEFAULT -1;
DECLARE _z_str varchar(50);
DECLARE _name varchar(50);
-- 创建临时表
DROP TABLE IF EXISTS p_test_msg;
create TEMPORARY table p_test_msg(
code varchar(50),
msg varchar(50)
);
set _name:= SUBSTRING_INDEX(pnames,',',1) ; -- _name 拆分后的值
while(_z_end <> -1) do
-- 插入临时表
insert into p_test_msg(code,msg) values(_z_num,_name);
-- 字符拆分
set _z_str := SUBSTRING_INDEX(pnames,',',_z_num);
set _z_num = -1 + _z_num;
if(_z_str = pnames) then
set _z_end := -1;
end if;
set _name:= SUBSTRING_INDEX(_z_str,',',1) ;
end while;
SELECT * FROM p_test_msg;
END;
执行过程: CALL p_test('a,b,c,d,e,f');
结果:
code msg
-1
a
-2
f
-3
e
-4
d
-5
c
-6
b