Using While in SQL Server

Hello everyone,

In this article, I will tell you about the use of While loop in SQL Server.

While loop in SQL Server is a construct that keeps a certain block in the loop by repeating. The loop continues to run until this condition is False. It is important to check and write while writing, otherwise there is a high probability of endless loops. You can see the example usage below.

--Defining variables

DECLARE @Number INT = 1;
DECLARE @Total INT = 0;

--Writing loop

WHILE @Number <= 10
BEGIN
    SET @Total = @Total + @Number; --We increase the number part by one after each loop. Because in the while part, our first number is checked.
    SET @Number = @Number + 1;
END;

--Toplam değerinin yazımı 

PRINT @Total;

When you run the above query, you will see a result similar to the one below.

Using While in SQL Server

As you can see, we have Number and Sum variables. Our number starts from 1. Our total value is also 0. In short, we are seeing a process that makes the sum of the numbers from 1 to 10. We add the Number value to the sum variable and increase the number value by one. Then our count is checked again in the while loop. The process continues in this way until it is less than and equal to 10. Then the while loop becomes false and the process terminates. Finally, we print our Total variable with Print and we get the sum of the numbers from 1 to 10.

Good luck to everyone in business and life.

148 Views

Yavuz Selim Kart

I try to explain what I know in software and database. I am still improving myself by doing research on many programming languages. Apart from these, I am also interested in Graphic Design and Wordpress. I also have knowledge about SEO and Social media management. In short, I am a determined person who likes to work hard.

You may also like...

Don`t copy text!