Search

Monday, September 29, 2014

Number of words in a string

In SQL Server there is not direct function to calculate the number of words in a string. 
But we can calculate the number of words in following way:

Option 1 :
CREATE FUNCTION dbo.UDFWordCount(@Text VARCHAR(8000))
RETURNS int
as
/*
SELECT dbo.UDFWordCount ('hello   world')
*/
BEGIN
     
    DECLARE @iCtr int, @iCtx INT, @Words int
    SELECT @iCtr = 1, @Words = 0 

    WHILE @iCtr <= DATALENGTH(@Text)
    BEGIN
        SELECT @iCtx = CHARINDEX(' ', @Text, @iCtr)
        if @iCtx = 0
        BEGIN
            SELECT @iCtx = DATALENGTH(@Text) + 1
        END
        IF SUBSTRING(@Text, @iCtr, @iCtx - @iCtr) <> ' '
              SELECT @Words = @Words + 1 
        SELECT @iCtr = @iCtx + 1
    END
    RETURN(@Words)
END
GO

SELECT dbo.UDFWordCount ('Microsoft SQL Server2008')
SELECT dbo.UDFWordCount ('Microsoft  SQL  Server  2008')

Option 2 :
DECLARE @strTemp VARCHAR(4000)
SELECT @strTemp = 'SQL Server 2005'
SELECT LEN(@strTemp) - LEN(REPLACE(@strTemp, ' ', '')) + 1

But in this option if word are separated by a single space than it will give you the correct result, If there is more than single space between words than it will give you  wrong result.


No comments:

Post a Comment