Find count of each characters in a string in SQL Server

In this article i am going to expalin the query used to count the no of characters in a string.

Below is the query which i used to do this operation.

First i have declared a variable and assigned some value to that variable.
Then using CTE i found the count of each characters in the input string. 

DECLARE @SplitList NVARCHAR(4000);

SELECT  @SplitList = 'Count Howmany Characters InString';

WITH    Listings (Position, CharacterSymbol) AS
        SELECT  1, SUBSTRING(@SplitList, 1, 1)
        UNION ALL
        SELECT s.Position + 1, SUBSTRING(@SplitList,s.Position + 1, 1)
        FROM    Listings AS s
        WHERE  s.Position <= LEN(@SplitList) - 1
SELECT  CASE WHEN s.CharacterSymbol = '' THEN 'Empty Space' ELSE s.CharacterSymbol END AS WCharacter , Count=COUNT(s.CharacterSymbol)
FROM    Listings AS s
GROUP BY s.CharacterSymbol


Post a Comment

Online Casino