SQL 如何查找某个字符串第N次出现的位置

if exists(select 1 from sysobjects where name='char_index')
drop function char_index

create function char_index(@string varchar(8000),@char varchar(10),@index smallint)
--@string:待查找字符串,@index:查找位置
returns smallint
as
begin
 
declare
 
@i tinyint,--当前找到第@i个
  @position tinyint--所在位置
  set @position=1;
 
set @i=0;
 
while charindex(@char,@string,@position)>0
 
begin
   
set @position=charindex(@char,@string,@position)+1;
   
set @i=@i+1;
   
if @i=@index
   
begin
    
return @position-1;
   
end
 
end
 
return 0;--0表示未找到
end

select dbo.char_index('sdf_dsf_dfgdg_ertr_erte','f_',2)

http://blog.csdn.net/zhou968/article/details/2760871

原文地址:https://www.cnblogs.com/Hdsome/p/2306523.html