Get Count of Number of Occurrences of Character in String

Applicability:

SQL Server 2000: Tested

SQL Server 2005: Tested

SQL Server 2008: Tested

SQL Server 2008R2: Tested

SQL Server 2012: Not Tested

Credits:

Author: ChillyDBA

Date: 17 Jul 2012

Description

Returns the count of all occurrences of the supplied character in the supplied string

Takes 3 parameters:

    • @Character - the character to be searched for

    • @String - the string to be searched

    • @IsCaseSensitive - 1 indicates that case sensitivity should be enforced during the search. Default 0.

NOTE1: For case sensitivity (CS), this will enforce CS in a non-CS database but will not relax CS in a CS database

NOTE2: The function utilises the function udf_NumbersTable. This has several versions, depending on SQL Server version.

Code

Function:

DROP FUNCTION dbo.udf_GetCountOfCharacterInString

GO

CREATE FUNCTION dbo.udf_GetCountOfCharacterInString

(

@Character CHAR(1), -- the character to search for

@String VARCHAR(MAX), -- the string to search

@IsCaseSensitive BIT = 0 -- is the search honor case sensitive?

)

RETURNS INT

AS

/**********************************************************

Purpose: Returns a count of the number of times the supplied

character occurs at in the supplied string.

NOTE: The case sensitive flag will only cause case sensitivity (CS) to

be applied in a non-CS DB. If will not apply non-CS in a CS DB

Utilises udf_NumbersTable to provide the required 'tally' table used

when parsing the string for matches

Author: ChillyDBA

History 17 Jul 2012 - Initial Issue

***********************************************************/

BEGIN

DECLARE @CountofOccurences INT

IF @IsCaseSensitive = 0

BEGIN

SELECT @CountofOccurences = MAX(RowNumber)

FROM

(

SELECT ROW_NUMBER() OVER (ORDER BY i ASC) AS RowNumber

FROM dbo.udf_NumbersTable(1, DATALENGTH(@String), 1)

WHERE i <= LEN(@String)

AND SUBSTRING(@String,i,1) = @Character

) AS x

END

ELSE

BEGIN

SELECT @CountofOccurences = MAX(RowNumber)

FROM

(

SELECT ROW_NUMBER() OVER (ORDER BY i ASC) AS RowNumber

FROM dbo.udf_NumbersTable(1, DATALENGTH(@String), 1)

WHERE i <= LEN(@String)

AND ASCII(SUBSTRING(@String,i,1)) = ASCII(@Character)

) AS x

END

RETURN @CountofOccurences

END

Test Code:

SELECT dbo.udf_GetCountOfCharacterInString('e', ',Element01,Element02,Element03,Element04,Element05,', 0)

SELECT dbo.udf_GetCountOfCharacterInString('e', ',Element01,Element02,Element03,Element04,Element05,', 1)