How to count duplicate characters using sql server
for example
place: chennai from that i want to count number of n's from chennai using sqlserver 2000
thanks
Rgds,
narasiman P
Loading
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Jignesh TrivediPosted Jun 28, 2012, 11:42 PM
In this case Scalar value function help you.
Try..
CREATE FUNCTION [dbo].[fnValue](@String varchar(max), @CharToFind char(1))
RETURNS INT
AS
BEGIN
DECLARE @idx int
DECLARE @countChar int
SET @countChar = 0
DECLARE @slice varchar(max)
SELECT @idx = 1
IF LEN(@String)<1 OR @String IS NULL
RETURN @countChar
WHILE @idx!= 0
BEGIN
SET @slice = LEFT(@String, 1)
IF(@slice=@CharToFind)
set @countChar = @countChar + 1
SET @String = right(@String,len(@String) - @idx)
IF LEN(@String) = 0
BREAK
END
RETURN @countChar
END
select dbo.fnValue('chennai','n')
--Output
--2
hope this help you.