Using the Nested While Loop in SQL Server

Hello everyone,

In this article, I will talk about the use of the nested while loop in SQL Server.

Using a nested while loop in SQL Server is the process of adding another loop inside a loop. The logic of the loop works as follows. The outermost loop returns first. Then it passes into the building inside. It doesn’t switch to the outer loop until the inner loop is complete. You can see the example usage below.

--Variable definition
DECLARE @Variable1 INT,
        @Variable2 INT;
--Assigning a value to variable 1
SET @Variable1 = 1;
--Loop start (outermost loop)
WHILE @Variable1 <= 2
    --Assigning a value to variable 2
    SET @Variable2 = 1; --Loop start (Inner loop)
    WHILE @Variable2 <= 10
        --Printing on the screen with the print operation
        PRINT CONVERT(VARCHAR, @Variable1) + ' * ' + CONVERT(VARCHAR, @Variable2) + ' = '
              + CONVERT(VARCHAR, @Variable1 * @Variable2);
        SET @Variable2 = @Variable2 + 1; --Increment variable 2 
    SET @Variable1 = @Variable1 + 1;

When you run the above code, you will see a multiplication table like the one below.

Using the Nested While Loop in SQL Server

First, there will be 1*1=1 operation and this operation will last until 1*10=10. Then it will go to 2*1=2 and this process will last until 2*10=20 and after this process the cycles will be completed and the process will be finished.

Good luck to everyone in business and life.


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!