Technical Article

Occurs

,

Returns the number of times a character expression occurs within another character expression.

cSearchExpression -- Specifies a character expression that OCCURS( ) searches for within cExpressionSearched.

cExpressionSearched -- Specifies the character expression OCCURS( ) searches for cSearchExpression.

OCCURS( ) returns 0 (zero) if cSearchExpression isn't found within cExpressionSearched.

CREATE FUNCTION dbo.Occurs 
(
@SearchExpression VARCHAR(255), 
@ExpressionSearch VARCHAR(4000)
)
RETURNS INT
AS
BEGIN
DECLARE @iRetVal INT
DECLARE @sSearchExp VARCHAR(255)
DECLARE @sExpSearch VARCHAR(4000)
DECLARE @iCurrentIndex INT

SET @sSearchExp = LOWER(@SearchExpression)
SET @sExpSearch = LOWER(@ExpressionSearch)
SET @iCurrentIndex = CHARINDEX(@sSearchExp, @sExpSearch)
SET @iRetVal = 0

IF @iCurrentIndex > 0 
BEGIN
SET @sExpSearch = RIGHT(@sExpSearch, LEN(@sExpSearch) - (@iCurrentIndex + LEN(@sSearchExp) - 1))
END

WHILE @iCurrentIndex > 0
BEGIN
SET @iRetVal = @iRetVal + 1 -- Increment Counter
SET @iCurrentIndex = CHARINDEX(@sSearchExp, @sExpSearch)
IF @iCurrentIndex > 0 
BEGIN
SET @sExpSearch = RIGHT(@sExpSearch, LEN(@sExpSearch) - (@iCurrentIndex + LEN(@sSearchExp) - 1))
END
END
RETURN @iRetVal  
END

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating