I ran into a weird situation today doing some one-time sql code. This nested loop doesn't seem to run the outer loop: it prints (0,0),(0,1),(0,2) and (0,3)
declare @i int, @j int
select @i = 0, @j = 0
while @i < 3 begin
while @j < 3 begin
select @i as i, @j as j
set @j = @j + 1
end
set @i = @i + 1
end
Am I missing something blatantly obvious?
SQL Server Nested Loops Join Explained A Nested Loops join is a logical structure in which one loop (iteration) resides inside another one, that is to say for each iteration of the outer loop all the iterations of the inner loop are executed/processed. A Nested Loops join works in the same way.
What Is a Nested While Loop? A nested while loop is a while statement inside another while statement. In a nested while loop, one iteration of the outer loop is first executed, after which the inner loop is executed. The execution of the inner loop continues till the condition described in the inner loop is satisfied.
SQL While loop syntax The while loop in SQL begins with the WHILE keyword followed by the condition which returns a Boolean value i.e. True or False. The body of the while loop keeps executing unless the condition returns false. The body of a while loop in SQL starts with a BEGIN block and ends with an END block.
Nested SQL While Loop SyntaxStep 1: First, it checks for the condition inside the first While loop. Step 2: It will verify the condition in the Nested SQL While Loop (second While loop). If the result is True, the code inside the second While loop begin… end will execute.
You are not resetting your j var for the next iteration
set @i = @i + 1 set @j = 0
You are not resetting @j.
declare @i int, @j int
select @i = 0, @j = 0 --<- Wrong place set @j
while @i < 3
begin
select @i, @j --<-test print, then you will know what happened~
--set @j = 0 --<- Right place to set @j
while @j < 3
begin
select @i as i, @j as j
set @j = @j + 1
end
set @i = @i + 1
end
The original result is 0/0 0/0 0/1 0/2 1/3 2/3
Well, the above answered, just add code for more detail, lol~
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With