【发布时间】:2014-06-10 15:07:42
【问题描述】:
我想在 SQL 中对整数的每个字符求和
例如。我有16273481 as INT
但是现在(不用复杂的方法)总和
1 + 6 + 2 + 7 + 3 + 4 + 8 + 1 = 32
【问题讨论】:
-
通过 Google 可以轻松找到很多解决方案。
我想在 SQL 中对整数的每个字符求和
例如。我有16273481 as INT
但是现在(不用复杂的方法)总和
1 + 6 + 2 + 7 + 3 + 4 + 8 + 1 = 32
【问题讨论】:
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
【讨论】:
使用余数运算符是否适合您的循环情况?
伪代码:
x = 16273481; 总和 = 0;
循环: 总和 = 总和 + (x % 10); x = (x / 10);
类似的东西?
【讨论】: