Using the Nested While Loop in SQL Server
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 BEGIN --Assigning a value to variable 2 SET @Variable2 = 1; --Loop start (Inner loop) WHILE @Variable2 <= 10 BEGIN --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 END; SET @Variable1 = @Variable1 + 1; END;
When you run the above code, you will see a multiplication table like the one below.
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.