Skip to content

Instantly share code, notes, and snippets.

@awayken
Created April 4, 2012 14:01
Show Gist options
  • Save awayken/2301299 to your computer and use it in GitHub Desktop.
Save awayken/2301299 to your computer and use it in GitHub Desktop.
Counts the number of times a given character shows up in a varchar
-- =============================================
-- Author: Miles Rausch
-- Create date: 12/8/2011
-- Description: Counts the number of times a given character shows up in a varchar
-- =============================================
CREATE FUNCTION getCharCount
(
@source varchar(MAX),
@char char(1)
)
RETURNS int
AS
BEGIN
DECLARE @count int
DECLARE @index int
SET @count = 0
SET @index = 0
WHILE @index < Len(@source)
BEGIN
IF LOWER(SUBSTRING(@source, @index, 1)) = LOWER(@char)
BEGIN
SET @count = @count + 1
END
SET @index = @index + 1
END
RETURN @count
END
GO
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment