26

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?

1
  • 1
    Thanks for this Q! I needed a big smile today. ;-) Commented Jan 7, 2010 at 13:55

3 Answers 3

50

You are not resetting your j var for the next iteration

 set @i = @i + 1
 set @j = 0
Sign up to request clarification or add additional context in comments.

4 Comments

Seven years later and here I am having the same duh moment
@dkwarr87 it's been 11 years and I'm keeping the tradition alive
I was going crazy until I found this. thanks!
15 years later, and here we are.
6

You are not resetting @j.

Comments

2
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~

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.