Wednesday, February 17, 2010

Count the string pattern in search

While developing a search engine, I had requirement of creating a function which can count the string occurrence. This function is written in T-SQL.

Here's a user-defined function that returns the number of times a given string exists on another string.  The first parameter is the string to be searched while the second parameter is the string to be searched for.
CREATE FUNCTION [dbo].[ufn_CountString]
( @pInput VARCHAR(8000), @pSearchString VARCHAR(100) )
RETURNS INT
BEGIN

RETURN (LEN(@pInput) -
LEN(REPLACE(@pInput, @pSearchString, ''))) /
LEN(@pSearchString)

END
GO
Description
Counting the number of times a string exists in another string is quite easy, as can be seen from the simple code of the user-defined function.  The process can be summarized into the following steps:
  1. REPLACE(@pInput, @pSearchString, '') - First step involves removing the string we are looking for from the input string by replacing it with an empty string.
  2. LEN(@pInput) - LEN() - After replacing the search string with an empty string, we now get the difference between the length of the original string and the new string with the replaced value.
  3. / LEN(@pSearchString) - The final step, which becomes the return value of the user-defined function, is to divide the result of the previous step with the length of the search string.  This will give use the number of times the search string exists within the other string.

No comments:

Post a Comment