• Here is my solution:

    DECLARE @i varchar(50)='122333444455555';

    WITH val(x,n) AS

    (

    SELECT LEFT(@i,LEN(@i)),'0'

    UNION ALL

    SELECT LEFT(x,LEN(x)-1),RIGHT(x,1) FROM val WHERE LEN(x)>0

    )

    SELECT SUM(CAST(n AS int)) FROM val

    What's cool is you can replace SELECT SUM(CAST(n AS int)) FROM val

    with SELECT * FROM val to see how it works.

    Result set:

    x n

    -------------------------------------------------- ----

    122333444455555 0

    12233344445555 5

    1223334444555 5

    122333444455 5

    12233344445 5

    1223334444 5

    122333444 4

    12233344 4

    1223334 4

    122333 4

    12233 3

    1223 3

    122 3

    12 2

    1 2

    1

    "I cant stress enough the importance of switching from a sequential files mindset to set-based thinking. After you make the switch, you can spend your time tuning and optimizing your queries instead of maintaining lengthy, poor-performing code."

    -- Itzik Ben-Gan 2001