Published on

July 26, 2010

Counting Occurrences of Characters in SQL Server

Are you a TSQL beginner looking for a solution to count the number of occurrences of characters in a string? Look no further! In this article, we will provide you with a quick method to count the occurrence of characters in any string using SQL Server.

Let’s start with a simple example:

DECLARE @LongSentence VARCHAR(MAX)
DECLARE @FindSubString VARCHAR(MAX)

SET @LongSentence = 'My Super Long String With Long Words'
SET @FindSubString = 'long'

SELECT (LEN(@LongSentence) - LEN(REPLACE(@LongSentence, @FindSubString, ''))) AS CntReplacedChars,
       (LEN(@LongSentence) - LEN(REPLACE(@LongSentence, @FindSubString, ''))) / LEN(@FindSubString) AS CntOccurrenceChars

The above code will return the following result:

CntReplacedCharsCntOccurrenceChars
22

In this example, we are counting the number of occurrences of the word ‘long’ in the string ‘My Super Long String With Long Words’. Both the CntReplacedChars and CntOccurrenceChars columns will have the same value since we are searching for a single word.

Let’s take another example where we want to count the occurrences of the character ‘o’ in the same string:

DECLARE @LongSentence VARCHAR(MAX)
DECLARE @FindSubString VARCHAR(MAX)

SET @LongSentence = 'My Super Long String With Long Words'
SET @FindSubString = 'o'

SELECT (LEN(@LongSentence) - LEN(REPLACE(@LongSentence, @FindSubString, ''))) AS CntReplacedChars,
       (LEN(@LongSentence) - LEN(REPLACE(@LongSentence, @FindSubString, ''))) / LEN(@FindSubString) AS CntOccurrenceChars

The result will be:

CntReplacedCharsCntOccurrenceChars
33

As you can see, both the CntReplacedChars and CntOccurrenceChars columns have the same value, indicating that the character ‘o’ appears three times in the string.

It’s important to note that you should ensure your strings do not have leading or trailing empty spaces. If they do, you can use the LTRIM or RTRIM functions to remove them before performing the count.

We hope this hint, along with a recursive CTE, will help you solve the T-SQL Challenge. Happy coding!

Click to rate this post!
[Total: 0 Average: 0]

Let's work together

Send us a message or book free introductory meeting with us using button below.