cdub
cdub

Reputation: 25711

Count all occurrences of text in a column

I want to count all occurrences of a particular word in a varchar(200) column.

My data is something like this:

ID    MyText
---   --------------------------------------
1     Hello how are you doing? Hello again.
2     This is great.
3     Hello my special person.

So I want SQL to do a like '%Hello%' and come back with the number 3. I don't care right now is for instance partial words are included and don't care right now on the like with wildcards. I only need this for some simple testing to validate some things.

Upvotes: 0

Views: 342

Answers (1)

Martin Smith
Martin Smith

Reputation: 453453

WITH T(ID,MyText) AS
(
SELECT 1, 'Hello how are you doing? Hello again.' UNION ALL
SELECT 2, 'This is great.' UNION ALL
SELECT 3, 'Hello my special person.'
)
SELECT *, 
       (LEN(MyText) - LEN(REPLACE(MyText, 'Hello', ''))) / LEN('Hello') AS Num
FROM T

Or

SELECT  SUM((LEN(MyText) - LEN(REPLACE(MyText, 'Hello', ''))) / LEN('Hello'))
FROM T

for an aggregate result

Upvotes: 6

Related Questions