mysql字符串字段按照逗號截取的存儲過程

找瞭好久,想通過mysql把字符串以‘,’拆分成多個數據,必須用存儲過程來實現這個功能,在這裡實現一下這個功能,例如將

轉為

排除裡面的N,然後把數字提取出來:

#查看已存在的存儲過程:SHOW PROCEDURE STATUS

# 函數:func_split_TotalLength

DELIMITER $$

DROP function IF EXISTS `func_split_TotalLength` $$

CREATE FUNCTION `func_split_TotalLength`

(f_string varchar(1000),f_delimiter varchar(5)) RETURNS int(11)

BEGIN

# 計算傳入字符串的總length

return 1+(length(f_string) – length(replace(f_string,f_delimiter,'')));

END $$

DELIMITER;

# 函數:func_split

DELIMITER $$

DROP function IF EXISTS `func_split` $$

CREATE FUNCTION `func_split`

(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;

# 存儲過程:splitString

DELIMITER $$

DROP PROCEDURE IF EXISTS `splitString` $$

CREATE PROCEDURE `splitString`

(IN f_string varchar(1000),IN f_delimiter varchar(10))

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` (`status` varchar(128) not null) DEFAULT CHARSET=utf8;

while i < cnt

do

set i = i + 1;

#插入除瞭'N'之外的所有數據

IF func_split(f_string,f_delimiter,i) != 'N' THEN

insert into tmp_split(`status`) values (func_split(f_string,f_delimiter,i));

END IF;

end while;

END$$

DELIMITER;

call splitString( (SELECT overdue_record_2year FROM Loan l WHERE l.papers_id = 231203199305030219 ORDER BY papers_id DESC LIMIT 1) ,",");

select * from tmp_split;

You May Also Like