That is because it comes after your loop... if you were to place that code above the loop (dynamic table), it works fine... but you cannot place it after the dynamic table without doing a completely separate query... the do while loop you have has set that variable several times.