How to use Nested WHILE Loop in SQL Server?

Leave a Comment
Here I will explain how to use nested while loops in SQL Server with example.
If you want to Nested while loops you need to write the query like this

DECLARE @loop1 INT
DECLARE @loop2 INT
SET @loop1 = 1
WHILE @loop1 <= 3
BEGIN   
SET @loop2 = 1   
WHILE @loop2 <= 2   
BEGIN       
PRINT CONVERT(VARCHAR, @loop1) + ' * ' + CONVERT(VARCHAR, @loop2)+ ' =
' + CONVERT(VARCHAR,@loop1 * @loop2)       
SET @loop2 = @loop2 + 1   
END   
SET @loop1 = @loop1 + 1
END

If you run above query you will get output like as shown below

Output



0 comments:

Post a Comment