var1 = 12345
output = 1+2+3+4+5 = 15
I tried the following
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;
Please help me achieve this with cte and any other methods other than the traditional loop are welcome
source
share