Try adding a feature.
CREATE FUNCTION CHARINDEX2 ( @TargetStr varchar(8000), @SearchedStr varchar(8000), @Occurrence int ) RETURNS int AS BEGIN DECLARE @pos INT, @counter INT, @ret INT set @pos = CHARINDEX(@TargetStr, @SearchedStr) set @counter = 1 if @Occurrence = 1 set @ret = @pos else begin while (@counter < @Occurrence) begin select @ret = CHARINDEX(@TargetStr, @SearchedStr, @pos + 1) set @counter = @counter + 1 set @pos = @ret end end RETURN(@ret) end
Then refer to the function as such ...
SELECT SUBSTRING('/one/two/three/whatever/testing', 0, dbo.CHARINDEX2('/', '/one/two/three/whatever/testing', 3))
Check out the article here for a better view :)
Scozzard
source share