Technical Article

Find Nth Occurrence of Character Function (Set Based)

,

This function was originally contributed by other visitors. Below is an example of a set based approach to the problem.

This script requires a numbers table (see SqlServerCentral article http://www.sqlservercentral.com/columnists/mcoles/2547.asp for more details)

Please note that this code is uses SQL2005 features

Enjoy!

Robert Cary

http://tsqlland.blogspot.com

if exists (
    select 1
    from dbo.sysobjects 
    where id = object_id(N'[dbo].[CHARINDEX3]') 
        and xtype in (N'FN', N'IF', N'TF'))
begin
    drop function [dbo].[CHARINDEX3]
end

GO

/*
Example:
SELECT dbo.CHARINDEX3('abb ', 'abb abb a', 3)
SELECT dbo.CHARINDEX3('bb a', 'abb abb a', 5)
SELECT dbo.CHARINDEX3('a', 'abbabba', 3)
SELECT dbo.CHARINDEX3('b', 'abbabba', 5)
If @occurance > the max Occurrence, the function will return the max Occurrence
*/
CREATE FUNCTION dbo.CHARINDEX3
(
    @TargetStr varchar(8000), 
    @SearchedStr varchar(8000), 
    @Occurrence int
)
RETURNS INT
AS
BEGIN
    DECLARE @ret INT

    SELECT TOP 1 @ret = Num 
    FROM
    (
        SELECT Ident = ROW_NUMBER() OVER (ORDER BY N.Num), N.Num 
        FROM dbo.Numbers N
        WHERE N.Num <= DATALENGTH(@SearchedStr)
            AND SUBSTRING(@SearchedStr, N.Num, DATALENGTH(@TargetStr)) = @TargetStr
    ) R 
    WHERE Ident <= @Occurrence
    ORDER BY Ident DESC

    RETURN @ret
END

Rate

5 (1)

You rated this post out of 5. Change rating

Share

Share

Rate

5 (1)

You rated this post out of 5. Change rating