title: Sum of digits of a number in sql server without using traditional loops like while
body: <pre><code>var1 = 12345
  output = 1+2+3+4+5 = 15
  </code></pre>
  
  <p>I tried the following </p>
  
  <pre><code>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 &lt;= len(@var1)
  )
  SELECT SUM(N) FROM SUMM;
  </code></pre>
  
  <p>Please help me with achieving it with cte and any other methods other than traditional looping are welcome</p>