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 with achieving it with cte and any other methods other than traditional looping are welcome
It's a fun exercise if a bit pointless.
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;
SELECT
SUM(CAST (SUBSTRING(STRING.B, V.NUMBER+1, 1)AS INT) )
FROM
(SELECT '12345' B) STRING
JOIN MASTER..SPT_VALUES V ON V.NUMBER < LEN(STRING.B)
WHERE V.TYPE = 'P'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With