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