when i create a function in sql server 2012 , in this function
CREATE FUNCTION howords (@str nvarchar(50), @word nvarchar(50))
RETURNS int
AS
BEGIN
DECLARE @tempstr nvarchar(max)
DECLARE @space int
DECLARE @count int
DECLARE @size int
SET @count = 0
WHILE (LEN(@str) >= 0)
BEGIN
SET @space = CHARINDEX(' ', @str, 1)
SET @tempstr = LEFT(@str, (@space - 1))
IF (@tempstr = @word)
SET @count = @count + 1
SET @size = LEN(@tempstr)
IF (((LEN(@str)) - @space) > 0)
SET @str = SUBSTRING(@str, @space + 1, ((LEN(@str)) - @space))
IF (((LEN(@str)) - @space) <= 0)
BEGIN
IF (@str = @word)
SET @count = 0
WHILE (LEN(@str) > 0)
BEGIN
SET @space = CHARINDEX(' ', @str + 1)
SET @tempstr = LEFT(@str, (@space - 1))
IF (@tempstr = @word)
SET @count = @count + 1
SET @size = LEN(@tempstr)
IF (((LEN(@str)) - @space) > 0)
SET @str = SUBSTRING(@str, @space + 1, ((LEN(@str)) - @space))
IF (((LEN(@str)) - @space) <= 0)
BEGIN
IF (@str = @word)
SET @count = @count + 1
BREAK
END
END
END
END
RETURN @count
END
when i exec this query
select dbo.howords ('hello my hello','hello' )
i want to give me count (2) but it give me an error
MSG 537 :Invalid length parameter passed to the LEFT or SUBSTRING function.
any help?