Basic Logics · Real Scenario Logic's · String Manipulation

Finding Number of Occurrences of a Particular Character in the String Using T-SQL

Introduction

In this blog post, we are going to see how can we easily find the number of occurrences of a Particular Character in the String Using T-SQL.

Finding Number of Occurrences of a Particular Character in the String

LOGIC

The Difference between the Length of String and Length of String without considering given particular character gives us the number of occurrences of a particular character in the string.

SQL SCRIPT

DECLARE @String VARCHAR(100),
		@Search_Char CHAR(1);

SELECT @String = 'Arulmouzhi',
	   @Search_Char='U';

SELECT 
CASE 
	WHEN CHARINDEX(@Search_Char,@String)>0 
	THEN ( LEN(@String) - LEN(REPLACE(@String,@Search_Char,'')) ) 
	ELSE 0
	END AS Particular_Char_Count;

IMAGE

Conclusion

Thus we saw how to find the number of occurrences of a Particular Character in the String easily using T-SQL. The above works well in both Azure SQL db and On-Premises.

Thanks for reading!

FOLLOW BLOG for interesting upcoming posts!

Advertisement

2 thoughts on “Finding Number of Occurrences of a Particular Character in the String Using T-SQL

    1. Yes Sir, it is used as best practice to avoid ‘Invalid length parameter passed to the LEFT or SUBSTRING function.’ in future string manipulation related codes. So used it here.

      Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s