我想在SQL
中对整数的每个字符求和例如。我有16273481 as INT
但是现在(没有复杂的方法)总和
1 + 6 + 2 + 7 + 3 + 4 + 8 + 1 = 32
答案 0 :(得分:3)
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
答案 1 :(得分:2)
使用余数运算符是否适合您的循环情况?
Pseuodo代码:
x = 16273481; sum = 0;
循环: sum = sum +(x%10); x =(x / 10);
这些方面的东西?