mysql中具有instr函数,但是这个函数只有两个参数,第一个参数为字符串,第二个参数为需要查询的字符串,返回的结果是第一次出现的位置。
但是orcal中的instr函数具有四个参数,前两个参数一样,但是后面可定义查询的起始位置和第几次出现。
CREATE DEFINER=`root`@`192.168.1.%` FUNCTION `instr1`(
IN_STR1 varchar(2500),#父字符串
IN_STR2 varchar(2500),#需要查询的字符串
IN_STARTPOS int(10),#起始位置
IN_NUM int(10) #次数
) RETURNS int(11)
BEGIN
###############################
## instr1('12325','2',4,1); 返回 4
##################################
declare str1_length int(10);
declare str2_length int(10);
declare result int(10) default 0;
declare postion int(10);
declare str1 varchar(2500);
declare NUM int(10);
declare i int(10);
set str1_length=length(IN_STR1);
set str2_length=length(IN_STR2);
#字符串长度+起始位置-1 大于父字符串 那么返回0
if(str1_length<(str2_length+IN_STARTPOS-1)) then return 0;end if;
##次数小于1
if IN_NUM<1 THEN RETURN 0; end if;
set str1=SUBSTR(IN_STR1,IN_STARTPOS);##获取第一次的父
set result=IN_STARTPOS-1;##获取初始位置
set NUM=IN_NUM;
lp1:while NUM>0 do
set postion=instr(str1,IN_STR2);
if postion=0 then set result=0; leave lp1; end if;##只要有一次没找到就是失败
set result=result+postion;
set NUM=NUM-1;
if NUM>0 THEN set str1=SUBSTR(str1,postion+1);end if;#获取下一次的父
end while;
return result;
END
这个函数没有实现起始位置为负数的时候,从右边进行查找的功能