How can count the string ?
for ex: If i have string like 'bhaskar' then i need like
b:1
h:1
a:2
s:1
k:1
r:1

please give any idea on that


Answer Posted / sanjay kumar dindaa

Declare @strInput as varchar(20)
declare @intLocal as int
declare @chrLocal as char
DECLARE @strLocal varchar(10)
DECLARE @strFinal varchar(100)

Set @intLocal=1
Set @chrLocal=1
Set @strInput='bhaskar'


If exists (Select 1 from sys.tables where name ='temp')
DROP TABLE temp
Create table temp(chrValue Char(1), Cnt Int)

while (@intLocal < len(@strInput) )
begin
set @chrLocal = Substring(@strInput,@intLocal,1)
IF (Select Count(1) from temp Where chrvalue=@chrLocal)> 0
UPDATE TEMP
Set Cnt=Cnt+1
Where chrValue=@chrLocal
else
Insert Into temp (chrValue, Cnt ) values ( @chrLocal,1)
set @intLocal = @intLocal+1
end


Set @strFinal=''
DECLARE @curLocal CURSOR
SET @curLocal = CURSOR FOR
Select ChrValue + ': '+ Cast(cnt as varchar(2)) from temp

OPEN @curLocal
FETCH NEXT
FROM @curLocal INTO @strLocal
WHILE @@FETCH_STATUS = 0
BEGIN
----PRINT @strLocal
Set @strFinal =@strFinal + ' ' + @strLocal
FETCH NEXT
FROM @curLocal INTO @strLocal
END
CLOSE @curLocal
DEALLOCATE @curLocal
PRINT @strFinal

Output :



(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)

(1 row(s) affected)
b: 1 h: 1 a: 2 s: 1 k: 1

Is This Answer Correct ?    1 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

Define self join?

714


What is intellisense?

691


What happens if strings are casted into wrong code pages in ms sql server?

695


What happens on checkpoint?

690


What are null values in ms sql server?

655






What is bcp? When does it used?

640


If we delete pack Spec what will be the status of pack Body ?

1048


Why normalization is used?

635


What is master database? : SQL Server Architecture

606


What are the advantages of the mirroring?

663


What objects does the fn_my_permissions function reports on? : sql server security

643


between cast and convert which function would you prefer and why?

644


What is temporary table in sql server? Why we use temp table?

600


How to rebuild the master database?

678


How to truncate the log in sql server 2012? : sql server database administration

670