Write a TSQL query which returns sum of 1-100

Vivaan 61 Reputation points
2022-01-27T17:13:20.123+00:00

Hi,

Kindly help me on t tsql code how to get sum of 1-100?

Developer technologies Transact-SQL
0 comments No comments
{count} votes

Accepted answer
  1. LiHong-MSFT 10,056 Reputation points
    2022-01-28T02:51:31.277+00:00

    Hi @Nandan Hegde
    Please also check this script using while loop:

    DECLARE @i INT,@sum INT  
    SET @i=1  
    SET @sum=0  
    WHILE @i<=100  
     BEGIN  
       SET @sum=@sum+@i  
       SET @i=@i+1  
     END  
    SELECT @sum  
    

    Best regards,
    LiHong


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


2 additional answers

Sort by: Most helpful
  1. Nandan Hegde 36,146 Reputation points MVP Volunteer Moderator
    2022-01-27T17:18:50.677+00:00

    Hey,
    There is a formula for sum of first n numbers :
    N *(N+1) /2

    So you can write in sql:

    Select 100*101/2

    0 comments No comments

  2. Erland Sommarskog 121.4K Reputation points MVP Volunteer Moderator
    2022-01-27T22:52:31.957+00:00

    Nandan is right on the money that you can use that formula. But else you need a table of numbers, which I have written about here: https://www.sommarskog.se/Short%20Stories/table-of-numbers.html.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.