How to find number of occurrence of char or word in a string ?

SQL Query

To get number of occurrence of a char in string 

DECLARE @myvar VARCHAR(20)
SET @myvar = ‘Hello World
SELECT LEN(@myvar) – LEN(REPLACE(@myvar,’l’,”)) AS [No-of-times char]

Number of times char ‘l’ is repeated 3 times

Output :  3



SQL Query  to get number of occurrence of a word in string 


DECLARE @myvar VARCHAR(MAX), @tosearch VARCHAR(20)
SET @myvar = ‘Hello Worlod, Hello World you’
SET @tosearch = ‘you’
SELECT (LEN(@myvar) – LEN(REPLACE(@myvar,@tosearch,”))) / LEN(@tosearch) AS [No-of-times word]

Number of times word ‘you’ is repeated 1 time

Output :  1





Published by arjunpremier

Software Engineer, Blogger,

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Design a site like this with WordPress.com
Get started