Pierre
Pierre

Reputation: 9052

SQL Sum of each character in a number

I want to sum each character of an integer in SQL

For instance. I have 16273481 as INT

But now (Without to complicated methods) sum

1 + 6 + 2 + 7 + 3 + 4 + 8 + 1 = 32

Upvotes: 0

Views: 1187

Answers (2)

typicalk
typicalk

Reputation: 86

Would using the remainder operator be suitable for your situation with a loop?

Pseuodo code:

x = 16273481; sum = 0;

Loop: sum = sum + (x % 10); x = (x / 10);

Something along those lines?

Upvotes: 2

Tom
Tom

Reputation: 7740

DECLARE @someInt INT = 16273481


-- you could put this all into a function
-- and then it would be reusable...
-- 
-- like... SELECT SumOfIndividualIntegers(16273481)

DECLARE @count INT = LEN(@someInt),
        @counter INT = 1

DECLARE @Sum INT = 0

WHILE @counter <= @count
BEGIN
    SELECT @sum += CAST(SUBSTRING(CAST(@someInt AS VARCHAR), @counter, 1) AS int)
    SELECT @counter += 1
END

SELECT @sum --32
-- and then you would RETURN @sum instead

Upvotes: 3

Related Questions