Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
 
 
 
        
Home       Members    Calendar    Who's On


Add to briefcase «««12345

Addition Of Digits Expand / Collapse
Author
Message
Posted Tuesday, September 25, 2012 3:55 AM


SSCommitted

SSCommittedSSCommittedSSCommittedSSCommittedSSCommittedSSCommittedSSCommittedSSCommitted

Group: General Forum Members
Last Login: Tuesday, September 9, 2014 1:49 AM
Points: 1,694, Visits: 19,551
Just for fun...

Using a lookup table improves performance, a bit suprising (for me at least).

    // Pre-calculated sums of 0 to 99
static readonly int[] TwoDigitSums = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
9, 10, 11, 12, 13, 14, 15, 16, 17, 18 };
// Handle NULLs by adding RETURNS NULL ON NULL INPUT to wrapper if required
[Microsoft.SqlServer.Server.SqlFunction]
public static int SumDigits(int Input)
{
return (Input >= 0 ? TwoDigitSums[Input % 100] +
TwoDigitSums[(Input / 100) % 100] +
TwoDigitSums[(Input / 10000) % 100] +
TwoDigitSums[(Input / 1000000) % 100] +
TwoDigitSums[(Input / 100000000) % 100]
: TwoDigitSums[-(Input % 100)] +
TwoDigitSums[(Input / -100) % 100] +
TwoDigitSums[(Input / -10000) % 100] +
TwoDigitSums[(Input / -1000000) % 100] +
TwoDigitSums[(Input / -100000000) % 100]);
}



____________________________________________________

How to get the best help on a forum

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

Never approach a goat from the front, a horse from the rear, or a fool from any direction.
Post #1363893
Posted Friday, October 25, 2013 12:34 PM
SSC Eights!

SSC Eights!SSC Eights!SSC Eights!SSC Eights!SSC Eights!SSC Eights!SSC Eights!SSC Eights!

Group: General Forum Members
Last Login: 2 days ago @ 3:09 PM
Points: 869, Visits: 2,396
I know this is an old thread, but please note that Celko and Improved Celko are the only ones (of the non-CLR ones in the test harness, as written) that survive crossing into BIGINT values (i.e. over 2147483647 but less than 9223372036854775807).

Trivial extensions of some of the others results in errors, probably due to rounding, at least near the maximums.
Post #1508569
« Prev Topic | Next Topic »

Add to briefcase «««12345

Permissions Expand / Collapse