0 Replies - 1671 Views - Last Post: 28 September 2008 - 05:41 PM

#1 PsychoCoder   User is offline

  • Google.Sucks.Init(true);
  • member icon

Reputation: 1659
  • View blog
  • Posts: 19,853
  • Joined: 26-July 07

Character count in MSSQL

Posted 28 September 2008 - 05:41 PM

Description: This is a user defined function to search for a particular character in a string and count how many times it appears in the string
CREATE FUNCTION dbo.udfCharacterCount(@input_str VARCHAR(1000), @search_for CHAR(1))
RETURNS INT
BEGIN
	DECLARE @char_count INT
	DECLARE @index INT

	SET @char_count = 0
	SET @index = 1

	--loop through the entire length of the input string
	WHILE @index <= LEN(@input_str)
		BEGIN
			/*
			see if the character at this index is the character
			we're looking for
			*/
			IF SUBSTRING(@input_str, @index, 1) = @search_for
				BEGIN
					--character found, increment count by 1
					SET @char_count = @char_count + 1
				END
			--increment counter to move to next character
			SET @index = @index + 1
		END
	--return the final count
	RETURN @char_count
END
GO



Is This A Good Question/Topic? 0
  • +

Page 1 of 1