T-SQL function to get word count
11/18/2008Similar 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.
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
0 comment(s)
Posted by Kevin J. Miller in:SQL Server