This article is half-done without your Comment! *** Please share your thoughts via Comment ***
Create a user defined function to count the total number of a word from the given string data.
Sample function execution:
1 |
select [dbo].[fn_GetWordCount]('I am Database Engineer and I am the owner of dbrnd.com') AS TotalWordCount |
Expected Output:
1 2 3 |
TotalWordCount -------------- 11 |
User defined function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
CREATE FUNCTION [dbo].[fn_GetWordCount] (@InputStringData VARCHAR(100)) RETURNS INT AS BEGIN DECLARE @i INT DECLARE @Char CHAR(1) DECLARE @PrevChar CHAR(1) DECLARE @Counter INT SET @i = 1 SET @Counter = 0 WHILE @i <= LEN(@InputStringData) BEGIN SET @Char = SUBSTRING(@InputStringData, @i, 1) SET @PrevChar = CASE WHEN @i = 1 THEN ' ' ELSE SUBSTRING(@InputStringData, @i - 1, 1) END IF @PrevChar = ' ' AND @Char != ' ' SET @Counter = @Counter + 1 SET @i = @i + 1 END RETURN @Counter END GO |
Please try the different solution for this puzzle and share it via comment...