小编典典

sql服务器中数字的数字总和,而无需使用while等传统循环

sql

var1 = 12345
output = 1+2+3+4+5 = 15

我尝试了以下

Declare @var1 int   = 12345,
        @Length int = len(12345)

;with SUMM as 
(
SELECT SUBSTRING(CAST(@var1 AS VARCHAR) ,1,@Length)%10 N
UNION ALL
SELECT SUBSTRING(CAST(@var1 AS VARCHAR) ,1,@Length-1))%10 N
FROM SUMM
WHERE @Length <= len(@var1)
)
SELECT SUM(N) FROM SUMM;

请帮助我用CTE实现它,欢迎使用除传统循环之外的任何其他方法


阅读 166

收藏
2021-03-10

共1个答案

小编典典

如果没有意义,这是一个有趣的练习。

DECLARE @var1 int   = 12345;

WITH i AS (
    SELECT @var1 / 10 n, @var1 % 10 d

    UNION ALL

    SELECT n / 10, n % 10
    FROM i
    WHERE n > 0
)
SELECT SUM(d)
FROM i;
2021-03-10