This article is written in response to provide hint to TSQL Beginners Challenge 14. The challenge is about counting the number of occurrences of characters in the string. Here is quick method how you can count occurrence of character in any string.
Here is quick example which provides you two different details.
- How many times the character/word exists in string?
- How many total characters exists in Occurrence?
Let us see following example and it will clearly explain it to you.
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, ''))) CntReplacedChars,
(LEN(@LongSentence) - LEN(REPLACE(@LongSentence, @FindSubString, '')))/LEN(@FindSubString) CntOccuranceChars
This will return following resultset.
CntReplacedChars    CntOccuranceChars -------------------- -------------------- 2                   2
If there is single word to find in the character, both the answer will be same. Here is the example of the same.
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, ''))) CntReplacedChars,
(LEN(@LongSentence) - LEN(REPLACE(@LongSentence, @FindSubString, '')))/LEN(@FindSubString) CntOccuranceChars
This will return following resultset.
CntReplacedChars    CntOccuranceChars -------------------- -------------------- 3                   3
I hope using this hint along with recursive CTE you will be able to solve the T-SQL Challenge. Additionally, make sure that your strings does not have leading or trailing empty spaces. If you have it, you may want to use LTRIM or RTRIM functions.
Reference: Pinal Dave (https://blog.sqlauthority.com)
43 Comments. Leave new
So with your example with the word ‘long’. Is there a way to pull out the word ‘long’ in a select statement for each time that it occurs? Perhaps separated by a column in the record? so the result would be ‘long’, ‘long’?
Hello. I wanted to point out that the results for your first example is incorrect. I copied and pasted the script to test it and the results are 8 and 2.
Thanks by the way, for your many examples. I have used a lot in the past.