• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
正在输入>
博客园    首页    新随笔    联系   管理    订阅  订阅

查找字符在字符串中第N次出现的位置

 
1.查找字符串 @find 在字符串 @str 中第 (@n) 次出现的位置。没有第 (@n) 次返回 0。
 1 返回@find在@str中第(@n)次出现的位置。没有第(@n)次返回0。
 2
 3 create function fn_find(@find varchar(8000), @str varchar(8000), @n smallint)
 4     returns int
 5 as
 6 begin
 7     if @n < 1 return (0)
 8     declare @start smallint, @count smallint, @index smallint, @len smallint
 9     set @index = charindex(@find, @str)
10     if @index = 0 return (0)
11     else select @count = 1, @len = len(@find)
12     while @index > 0 and @count < @n
13         begin
14             set @start = @index + @len
15             select @index = charindex(@find, @str, @start), @count = @count + 1
16         end
17     if @count < @n set @index = 0
18     return (@index)
19 end
20 go
21 declare @str varchar(100)
22 set @str='A,B,C,D,A,B,C,D,C,D,B,A,C,E'
23 select dbo.fn_find('A',@str,1) as one, dbo.fn_find('A',@str,2) as two, dbo.fn_find('A',@str,3) as three, dbo.fn_find('A',@str,4) as four

 

posted @ 2019-01-18 11:58  正在输入>  阅读(2698)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3