Stored procedure with SUBSTRING in WHILE loop SQL Server 2005

Below given stored procedure will count occurrence of given character in given string.

–stored procedure which will count occurence given character in @CountChar

–from @string variable

CREATE PROC CharCount(@String VARCHAR(50),@CountChar VARCHAR(1))

AS

BEGIN

DECLARE @counter INT

DECLARE @finalCount INT

SET @finalCount=0

SET @counter=LEN(@String)

WHILE @counter>=0

BEGIN

IF @CountChar=SUBSTRING(@String,@counter,1)

BEGIN

SET @finalCount=@finalCount+1

END

SET @counter=@counter1

END

SELECT @finalCount

END

GO

–check the SP

EXEC CharCount ‘ritesh shah from SQLHub.Com’,‘h’

Happy Programming!!!

Reference: Ritesh Shah
http://www.sqlhub.com
Note: Microsoft Books online is a default reference of all articles but examples and explanations prepared by Ritesh Shah, founder of
http://www.SQLHub.com

Advertisements