Technical Article

Get given character's position from a string

,

--test

select dbo.f_firstposition('abc,def,ccc,ged',',',1)
go
Result:4
select dbo.f_firstposition('abc,def,ccc,ged',',',2)
go
Result:8
select dbo.f_firstposition('abc,def,ccc,ged',',',3)
go
Result:12
select dbo.f_firstposition('abc,def,ccc,ged',',',4)
go
Result:0

create function dbo.f_firstposition
(@Str varchar(8000),@StrSep varchar(10),@AppPos int)
returns int
begin
 declare @i int
 declare @ii int
 set @Str=rtrim(ltrim(@Str))
 set @i=1
 select @ii=charindex(@StrSep,@Str)
 if @i=@AppPos
 return @ii
 else
 while @AppPos>@i
 begin
 if charindex(@StrSep,right(@Str,len(@Str)-@ii))<>0
 select @ii=charindex(@StrSep,right(@Str,len(@Str)-@ii))+@ii
 else
 set @ii=0
 set @i=@i+1
 end

 return @ii
end
go

Rate

2.33 (3)

You rated this post out of 5. Change rating

Share

Share

Rate

2.33 (3)

You rated this post out of 5. Change rating