SQL Server get number of occurrences of a character in a string
Published in
Apr 13, 2022
In SQL Server its a common requirement to count how many times a particular character is appeared in a string
in “Hello friend” , “l” occurred 2 times
To find the number of occurrences , lets use a logic by
- Take total length of the string , say its 12 , in our case
- Now remove all “l” s
- Find difference before and after removing “l”
- This difference is the number of occurrence of “l” in the string “Hello friend”
Example
select len('Hello friend')12select replace('Hello friend','l','')10select len('Hello friend') - len(replace('Hello friend','l',''))2