SQL Server: Word count in a string

I needed count of words available in each record of a specific column. So that I could order on the record string which has highest words. Below function will does the task. This function will not exclude special chars or numbers.
CREATE FUNCTION [dbo].[WordCount] ( @InputString VARCHAR(4000) )
RETURNS INT
AS
BEGIN

DECLARE @Index          INT
DECLARE @Char           CHAR(1)
DECLARE @PrevChar       CHAR(1)
DECLARE @WordCount      INT

SET @Index = 1
SET @WordCount = 0

WHILE @Index <= LEN(@InputString)
BEGIN
    SET @Char     = SUBSTRING(@InputString, @Index, 1)
    SET @PrevChar = CASE WHEN @Index = 1 THEN ' '
                         ELSE SUBSTRING(@InputString, @Index - 1, 1)
                    END

    IF @PrevChar = ' ' AND @Char != ' '
        SET @WordCount = @WordCount + 1

    SET @Index = @Index + 1
END

RETURN @WordCount

END
GO

If we need to exclude numbers and non printable chars, then below function can be used
CREATE function fn_how_many_words(
    @source varchar(max) )
    returns int
as
begin
    declare @start int

    --  break any multiple spaces down
    while 1=1
    begin
        set @start = len( replace( @source, '  ', ' ' ) )
        set @source = replace( @source, '  ', ' ' )
        if @start = len( replace( @source, '  ', ' ' ) )
            break

    end
    --  get rid of any non letters and numbers
    set @start = 1
    while @start <= 255
    begin
        if @start not between ascii( 'a' ) and ascii( 'z' )
           and @start not between ascii( 'A' ) and ascii( 'Z' )
           and @start not between ascii( '0' ) and ascii( '9' )
           and @start <> ascii( ' ' )

           set @source = replace( @source, char( @start ), '' )
         set @start = @start + 1
    end

    return( len( @source ) - len( replace( @source, ' ', '' ) ) + 1 )
end

1 comment:

  1. It is the best way to cure the anger and stress. Sometimes, harsh words and angriness can break our relationship. And I think playing this clicking game can save your relation at the time of anger. According to my opinion, open and play the click speed test during your hard time. I guarantee that you will feel relax and find your solution to the problem as well.
    spacebar counter

    ReplyDelete