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

What is service broker? : sql server database administration

568


How do I save a stored procedure in sql server?

485


What is difference between index and primary key?

574


How to modify an existing stored procedure in ms sql server?

521


What is a deadlock and what is a live lock?

564






What are the different authentication modes in sql server?

560


What is the difference between locking and multi-versioning?

517


You have a table with close to 100 million records recently, a huge amount of this data was updated now, various queries against this table have slowed down considerably what is the quickest option to remedy the situation?

475


What does it mean to invest in the index?

498


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

524


Explain different backup plans?

523


How to find the version of sql server? : sql server database administration

619


How many cores do I need for sql server 2016?

498


What happens if null values are involved in bitwise operations?

593


What are the new scripting capabilities of ssms? : sql server management studio

537