现在的位置: 首页 > 综合 > 正文

mysql中split函数

2018年01月24日 ⁄ 综合 ⁄ 共 2225字 ⁄ 字号 评论关闭

在mysql中并没有split函数,需要自己写:

1)获得按指定字符分割的字符串的个数:

    

Sql代码  收藏代码
  1. DELIMITER $$  
  2.   
  3. DROP FUNCTION IF EXISTS `sims`.`func_get_split_string_total`$$  
  4.   
  5. CREATE DEFINER=`root`@`localhost` FUNCTION `func_get_split_string_total`(  
  6. f_string varchar(1000),f_delimiter varchar(5)  
  7. RETURNS int(11)  
  8. BEGIN  
  9.   declare returnInt int(11);  
  10.   if length(f_delimiter)=2  then  
  11.      return 1+(length(f_string) - length(replace(f_string,f_delimiter,'')))/2;  
  12.   else      
  13.      return 1+(length(f_string) - length(replace(f_string,f_delimiter,'')));  
  14.   end if;  
  15. END$$  
  16.   
  17. DELIMITER ;  

   例:func_get_split_string_total('abc||def||gh','||')  结果为3  

 

    2)得到第i个分割后的字符串。

 

   

Sql代码  收藏代码
  1. DELIMITER $$  
  2.   
  3. DROP FUNCTION IF EXISTS `sims`.`func_get_split_string`$$  
  4.   
  5. CREATE DEFINER=`root`@`localhost` FUNCTION `func_get_split_string`(  
  6. f_string varchar(1000),f_delimiter varchar(5),f_order intRETURNS varchar(255) CHARSET utf8  
  7. BEGIN  
  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.   
  13. DELIMITER ;  

   例如:func_get_split_string('abc||def||gh','||',2) 为def

 

 

   3) 需求:A表中的一个字段值为1||2, 在select 时要通过和B字典表的关联得到a,b

   

Sql代码  收藏代码
  1. CREATE DEFINER=`root`@`localhost` FUNCTION `getDictName`(v_str varchar(100)) RETURNS varchar(100) CHARSET utf8  
  2. BEGIN  
  3.             
  4.           DECLARE i int(4);  
  5.           DECLARE dictCode varchar(100);  
  6.           DECLARE dictName varchar(100);  
  7.           DECLARE returnStr varchar(100);   
  8.           
  9.           set i = 1;  
  10.           set returnStr = '';        
  11.             
  12.           if(v_str is null or length(v_str)=0) then  
  13.                return returnStr;  
  14.           else  
  15.             
  16.           while i<=func_get_split_string_total(v_str,'||')  
  17.           do  
  18.                set dictCode = func_get_split_string(v_str,'||',i);  
  19.             
  20.                select names into dictName from sims_dd_dict where code = dictCode;   
  21.             
  22.                set returnStr = concat(returnStr,',',dictName);  -- 这里要用中文的逗号,否则导出EXCEL的时候会串行,因为程序中是以逗号分隔的  
  23.           set i = i+1;  
  24.           end while;  
  25.              
  26.           set returnStr = subString(returnStr,2);            
  27.           return returnStr;  
  28.              
  29.           end if;  
  30.     END$$  

抱歉!评论已关闭.