0

I got stuck in a nested loop and would appreciate some advice.

Declare @monthNumber as Integer, @loopCounter as Integer

Set @monthNumber = 0
Set @loopCounter = 1

While @monthNumber <= 13 Begin
     While @loopCounter <=100 Begin
     @loopCounter = @loopCounter +1
     End
 @monthNumber = @monthNumber + 1
 End

I've abbreviated my code to the sample above; I have two loops in my main SQL query. The inner loop is to identify different records in my table 100 times, and the outer loop is to basically add one extra month to the @monthNumber variable so that when the code runs, I return 100 records for each of the 13 months into one table. When I run the code, the first inner loop runs perfectly, but ends without continuing to the next month via adding a 1 to the @monthNumber. Any suggestions?

1
  • You might want to add a tag to your question indicating what version of SQL you are using. Commented Apr 29, 2015 at 0:08

1 Answer 1

1

You do not reset the @loopCount variable back to 1:

Declare @monthNumber as Integer, @loopCounter as Integer

Set @monthNumber = 0
Set @loopCounter = 1

While @monthNumber <= 13 Begin
     While @loopCounter <=100 Begin
     @loopCounter = @loopCounter +1
     End
 @monthNumber = @monthNumber + 1
 Set @loopCounter = 1
 End
Sign up to request clarification or add additional context in comments.

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.