环境:MySQL 5.5
需求:将"apple,orange,water melon,banana"字符串以","分隔后各单词或词组的首字母大写
实现:写了个函数:
drop function if exists fun_initial_upper;
delimiter $$
create function fun_initial_upper(sourceStr varchar(255),delim varchar(10))
returns varchar(255)
begin
declare destinationStr varchar(255) default ''; #返回结果字符串
declare size integer default 0; #以delim为分隔符得到的单词或词组的个数+1
declare tmpStr varchar(255); #中间变量
declare len integer default 0; #单词或词组的长度
declare changeDelim bool default false; #是否改变分隔符(针对输入空格符)
if delim = '' || delim regexp '[[:blank:]]' then #正则匹配分隔符是否是空格符
set sourceStr = replace(sourceStr,delim,'//,');
set delim = '//,'; #自定义分隔符
set changeDelim = true;
end if;
set sourceStr = concat(delim,sourceStr); #初始化源字符串
set size = length(sourceStr)-length(replace(sourceStr,delim,''))+1;
loop_label: loop
if size > 0 then
set tmpStr = substring_index(sourceStr,delim,size-1);
set len = char_length(substring_index(sourceStr,delim,size)) - char_length(tmpStr)-char_length(delim);
if len > 0 then
set tmpStr = trim(substring(sourceStr,char_length(tmpStr)+char_length(delim)+1,len));
set tmpStr = concat(upper(left(tmpStr,1)),substring(tmpStr,2,(length(tmpStr)-1)));
set destinationStr = concat(delim,tmpStr,destinationStr);
end if;
set size = size - 1;
else
leave loop_label;
end if;
end loop;
set destinationStr = concat(substring(destinationStr,char_length(delim)+1,(length(destinationStr)-1)));#去除开始处的delim,与set sourceStr = concat(delim,sourceStr)相对
if changeDelim then
set destinationStr = replace(destinationStr,delim,' ');
end if;
return destinationStr;
end
$$
delimiter ;
函数:
- regexp:正则匹配
- concat(str1,str2,...):字符串连接(将字符串str1,str2,...连接)
- length(str):字符串str的长度
- replace(str,from_str,to_str):字符串替换(字符串str中的所有的from_str的被to_str代替)
- substring_index(str,delim,count):在定界符delim以及count出现前,从字符串str返回子字符串.若count为正值,则返回最终定界符(从左边开始)左边的一切内容.若count为负值,则返回定界符(从右边开始)右边的一切内容。
- char_length(str):返回字符串str的字符长度
- trim(str):字符串首尾去空值
- upper(str):字符串各字符转化为大写
- substring(str,pos,len):子串(获得字符串str以pos为起始位置,长度为len的子串)
结果: