Program to find sum of digits in TSQL

Rajnilari2015
Posted by Rajnilari2015 under Sql Server category on | Points: 40 | Views : 240
;WITH getDigitsCTE AS (
SELECT
Quotient = @Number / 10
,Remainder = @Number % 10

UNION ALL

SELECT
Quotient / 10
, Quotient % 10

FROM getDigitsCTE

WHERE Quotient > 0
)

SELECT
[Sum of digits]=SUM(Remainder)
FROM getDigitsCTE


/*

Sum of digits
---------------
45

*/

Comments or Responses

Login to post response