利用MySQL存储过程分割字符串

(转)http://tec.5lulu.com/detail/104krn1e6p2w78d77.html

现有一段字符串,如apple,banana,orange,pears,grape,要把它按照逗号(,)分割成:

apple
banana
orange
pears
grape

       然后使用where in()方法可以查询。

1、具体函数: 

  1. # 函数:func_split_TotalLength
  2. DELIMITER $$
  3. DROP function IF EXISTS `func_split_TotalLength` $$
  4. CREATE DEFINER=`root`@`%` FUNCTION `func_split_TotalLength`
  5. (f_string varchar(1000),f_delimiter varchar(5)) RETURNS int(11)
  6. BEGIN
  7. # 计算传入字符串的总length
  8. return 1+(length(f_string) - length(replace(f_string,f_delimiter,'')));
  9. END$$
  10. DELIMITER;
  1. # 函数:func_split
  2. DELIMITER $$
  3. DROP function IF EXISTS `func_split` $$
  4. CREATE DEFINER=`root`@`%` FUNCTION `func_split`
  5. (f_string varchar(1000),f_delimiter varchar(5),f_order int) RETURNS varchar(255) CHARSET utf8
  6. BEGIN
  7. # 拆分传入的字符串,返回拆分后的新字符串
  8. declare result varchar(255) default '';
  9. set result = reverse(substring_index(reverse(substring_index(f_string,f_delimiter,f_order)),f_delimiter,1));
  10. return result;
  11. END$$
  12. DELIMITER;
  1. # 存储过程:splitString
  2. DELIMITER $$
  3. DROP PROCEDURE IF EXISTS `splitString` $$
  4. CREATE PROCEDURE `splitString`
  5. (IN f_string varchar(1000),IN f_delimiter varchar(5))
  6. BEGIN
  7. # 拆分结果
  8. declare cnt int default 0;
  9. declare i int default 0;
  10. set cnt = func_split_TotalLength(f_string,f_delimiter);
  11. DROP TABLE IF EXISTS `tmp_split`;
  12. create temporary table `tmp_split` (`status` varchar(128) not null) DEFAULT CHARSET=utf8;
  13. while i < cnt
  14. do
  15. set i = i + 1;
  16. insert into tmp_split(`status`) values (func_split(f_string,f_delimiter,i));
  17. end while;
  18. END$$
  19. DELIMITER;

2、测试是否能成功分割

  1. call splitString("apple,banana,orange,pears,grape",",");
  2. select * from tmp_split;


       运行结果如下,说明分割成功:

mysql> call splitString("apple,banana,orange,pears,grape",",");
select * from tmp_split;
Query OK, 1 row affected

+--------+
| status |
+--------+
| apple  |
| banana |
| orange |
| pears  |
| grape  |
+--------+
5 rows in set

mysql>

3、应用where in()查询

    1. # 先传入字符串,分割后保存在临时表tmp_split中
    2. call splitString("apple,banana,orange,pears,grape",",");
    3. # 将查询的结果作为其他查询的条件来使用
    4. select * from fruit where in(select * from tmp_split);

你可能感兴趣的:(Mysql存储过程)