• SQL Kiwi (9/21/2012)


    This is about twice as fast for me:

    Source:

    [font="Courier New"]    public static int SumDigits(int Input)

        {

            int sum = 0;

            for (int n = System.Math.Abs(Input); n > 0; sum += n % 10, n /= 10) ;

            return sum;

        }

    [/font]

    Unrolling the loop yields a small performance gain. Still doesn't handle NULLs or -2147483648 though.

    [Microsoft.SqlServer.Server.SqlFunction]

    public static int SumDigits(int Input)

    {

    int n = (Input >= 0 ? Input : -Input);

    return (n % 10) +

    ((n/10) % 10) +

    ((n/100) % 10) +

    ((n/1000) % 10) +

    ((n/10000) % 10) +

    ((n/100000) % 10) +

    ((n/1000000) % 10) +

    ((n/10000000) % 10) +

    ((n/100000000) % 10) +

    ((n/1000000000) % 10);

    }

    ____________________________________________________

    Deja View - The strange feeling that somewhere, sometime you've optimised this query before

    How to get the best help on a forum

    http://www.sqlservercentral.com/articles/Best+Practices/61537