查找‘B’在字符串中‘ABCDBCBSEB’第二次出现的位置

 1 create function func_find
 2 (
 3 @S_str varchar(8000),     --源字符串
 4 @T_str varchar(8000),     --目标字符串,即需要查找的字符串
 5 @n int                             --第几次出现
 6 )
 7 returns int
 8 as
 9 begin
10    declare @idx int
11    ;with cte(Str,CharIdx,Times) as
12    (
13       select @S_str,CHARINDEX(@T_str,@S_str,1) as CharIdx,1 as Times
14       union all
15       select @S_str,CHARINDEX(@T_str,@S_str,CharIdx+1) as CharIdx,Times+1 
16       from cte where CHARINDEX(@T_str,@S_str,CharIdx+1)>0
17    )
18    select @idx=isnull(CharIdx,0) from cte where Times=@n
19    return @idx
20 end
21 go
22 --select dbo.func_find('ABCDBCBSEB','B',2)

 

  

 posted on 2017-05-02 16:46  会飞的金鱼  阅读(1880)  评论(0)    收藏  举报