Technical Article

Function for String Occurences Count

,

This function is used to get the particular string occurences count from the given input string.

--examples

select dbo.fn_get_string_occurences_count('The quick brown fox jumps over the lazy dog','brown')

select dbo.fn_get_string_occurences_count('The quick brown fox jumps over the lazy dog','the')

Regards,

Vignesh Arulmani

create function dbo.fn_get_string_occurences_count (
@inputstring varchar(max),
@searchstring varchar(256)
)returns int 
as
begin
      declare @occurences as int,@position as int,@returnValue int

      set @occurences = 0
      set @position = 0

      while @position < len(@inputstring)
      begin
            if charindex(@searchstring, @inputstring, @position) > 0
            begin
               set @occurences = @occurences + 1
               set @position = charindex(@searchstring, @inputstring, @position)
            end
            set @position = @position+1
      end
  
  set @returnValue = @occurences
      
  return @returnValue
end

--examples
select dbo.fn_get_string_occurences_count('The quick brown fox jumps over the lazy dog','brown')
select dbo.fn_get_string_occurences_count('The quick brown fox jumps over the lazy dog','the')

Rate

1.25 (4)

You rated this post out of 5. Change rating

Share

Share

Rate

1.25 (4)

You rated this post out of 5. Change rating