Situatie
Mai jos am creat o functie care returneaza numarul de cuvinte care se afla intr-o fraza. Functia poate fi rulata, desigur, avand ca parametru si numele unei coloane dintr-o tabela, cu conditia ca acea coloana sa fie de tipul varchar.
Solutie
— select dbo.BD_WordCount_fct (‘a fost odata ca niciodata. Daca nu ar’)
CREATE FUNCTION dbo.BD_WordCount_fct ( @Param 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(@Param)
BEGIN
SET @Char = SUBSTRING(@Param, @Index, 1)
SET @PrevChar = CASE WHEN @Index = 1 THEN ‘ ‘
ELSE SUBSTRING(@Param, @Index – 1, 1)
END
IF @PrevChar = ‘ ‘ AND @Char != ‘ ‘
SET @WordCount = @WordCount + 1
SET @Index = @Index + 1
END
RETURN @WordCount
END
Leave A Comment?