Wednesday 25 August 2010

SQL Snippet - How to count the number of characters in a string

I've come across a number of methods to count the number of characters in a string in SQL Server, but this is by far the most clever:


SELECT LEN('How to count no. of o') - LEN( REPLACE('How to count no. of o','o','') )

The replace function replaces all 'o's with '', therefore removing them.

The difference in lengths is therefore the number of 'o's.

No comments: