Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is wrong with this nested WHILE loop in SQL

Tags:

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?

like image 202
edosoft Avatar asked Jan 07 '10 13:01

edosoft


People also ask

What is nested loop in SQL Server?

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.

Why we use nested while loop?

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.

How can use while loop in select statement in SQL Server?

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.

How do you use multiple while loops in SQL?

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.


3 Answers

You are not resetting your j var for the next iteration

 set @i = @i + 1  set @j = 0 
like image 167
almog.ori Avatar answered Sep 22 '22 04:09

almog.ori


You are not resetting @j.

like image 27
ozczecho Avatar answered Sep 19 '22 04:09

ozczecho


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~

like image 41
Chjquest Avatar answered Sep 22 '22 04:09

Chjquest