Count Words Function
In SQL Server, and I believe as well as in other databases, there's no built-in
function that will return the number of words a given string contains.
Assuming that the space character separates each word, counting the number of
words in a string can be performed using the following query on the given
definition of a Health Insurance:
DECLARE @String VARCHAR(4000)
SET @String = 'Health Insurance is an insurance against
expenses incurred through illness of the insured.'
SELECT LEN(@String) - LEN(REPLACE(@String, ' ', '')) + 1
This query will return a value of 13, which is the number of words in the given
string. But if the words are separate by not just a single space
character but by multiple spaces, then this will return an incorrect result as
can be seen from the following:
DECLARE @String VARCHAR(4000)
SET @String = 'Health Insurance'
SELECT LEN(@String) - LEN(REPLACE(@String, ' ', '')) + 1
There are three spaces between the words "Health" and "Insurance" and the value
returned by the query is 4 instead of just 2. The reason why it returns a
value of 4 is because the query simply counts the number of spaces in the
string and adds 1 to it. So since there are 3 spaces between the words,
the result becomes 4.