分类: Mysql/postgreSQL
2008-02-26 10:08:46
DELIMITER $$
DROP FUNCTION IF EXISTS `test`.`func_get_string_count`$$
CREATE FUNCTION `test`.`func_get_string_count`(
f_str varchar(8000), f_substr varchar(255))
RETURNS int
BEGIN
-- Created by david yeung 20080226.
declare total int default 0;
declare remain_str varchar(8000) default '';
set remain_str = f_str;
while instr(remain_str,f_substr) > 0
do
set total = total + 1;
set remain_str = substring(remain_str,instr(remain_str,f_substr) + char_length(f_substr));
end while;
return total;
END$$
DELIMITER ;
调用结果:
select func_get_string_count('I love you love,""&&&& I love, I hate, love love love','love') as substr_count;
substr_count |
6 |
set @str = 'I love you love,""&&&& I love, I hate, love love love';
set @sub_str = 'love';
select ceiling((char_length(@str) - char_length(replace(@str,@sub_str,'')))/char_length(@sub_str)) as substr_count;
结果:
substr_count |
6 |