edosoft
edosoft

Reputation: 17281

What is wrong with this nested WHILE loop in SQL

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?

Upvotes: 26

Views: 35184

Answers (3)

Chjquest
Chjquest

Reputation: 335

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~

Upvotes: 2

ozczecho
ozczecho

Reputation: 8869

You are not resetting @j.

Upvotes: 6

almog.ori
almog.ori

Reputation: 7889

You are not resetting your j var for the next iteration

 set @i = @i + 1
 set @j = 0

Upvotes: 50

Related Questions