1. 程式人生 > 實用技巧 >獲取字串指定字元的第n次出現位置

獲取字串指定字元的第n次出現位置

create function uf_findx (@text nvarchar(max),@find_x varchar(200),@find_n int)
returns int
as
begin
--第n位無效引數返回0
if @find_n<1
return (0);
--字串不含指定字串返回0
else if CHARINDEX(@find_x,@text)=0
return (0);
else
begin

declare @index int =1,@count_nd int=1,@len int=1
--迴圈獲取第n個指定字串位置

while @find_n>[email protected]_nd
begin

select @index=CHARINDEX(@find_x,@text,@len)
set @[email protected]_nd+1
set @[email protected]+1
--第n個指定字串超過最大個數直接返回0
if @index=0
return (0);

end
end
return (@index);
end