Similar in approach to the previous uf_charCount function, the following function returns the number of words in a string, assuming a space token as word separator.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
CREATE FUNCTION [dbo].[uf_wordCount] (@string varchar(8000)) RETURNS SMALLINT /* Purpose: returns the number of words in @string Author: Kevin J. Miller (www.websolete.com) Example: SELECT dbo.uf_wordCount('four score and seven years ago') would return: 6 */ AS BEGIN SET @string = LTRIM(RTRIM(ISNULL(@string,''))); IF LEN(@string) = 0 RETURN 0; -- return the difference in length after stripping spaces, this is the word count RETURN ((LEN(@string) + 1) - LEN(REPLACE(@string,' ',''))); END |