MySQL 存储过程 根据分隔符拆分字符串

DELIMITER $$

CREATE DEFINER=`root`@`%` PROCEDURE `proc_split_Id`(in selectIds blob(65535),
in splitChar varchar(2))
BEGIN
set @i=0; 
CREATE TEMPORARY TABLE if not exists Id_Result_s(Id long NOT NULL);
truncate table Id_Result_s;
SET @cnt = 1+(LENGTH(selectIds) - LENGTH(REPLACE(selectIds,splitChar,''))); 
set @i=1; 
	start transaction;
    WHILE @i <=@cnt DO          
        SET @result = REPLACE(SUBSTRING(SUBSTRING_INDEX(selectIds, splitChar, @i),
       LENGTH(SUBSTRING_INDEX(selectIds, splitChar, @i -1)) + 1),
       splitChar, '');  
       INSERT INTO Id_Result_s(Id) VALUES (@result );
		SET @i = @i + 1;   
    END WHILE;  
	commit;    
END

selectIds为需要拆分的字符串,splitChar为分隔符. 拆分的结果保存在临时表Id_Result_s中.

while中有insert语句,循环插入.在while前后加上start transaction和commit可以提高效率.

你可能感兴趣的:(MySQL)