Posts

Showing posts from February, 2016

T-SQL Local Variable Scoping in a Loop

I learned something about T-SQL variable scoping that I did not previously recognize. Within a loop, you can declare a variable. When you run the loop, things function fine - you don't get any "hey, you already declared that variable" errors. In my mind that means the variable must be locally scoped to the loop, and perhaps would get reset on each pass through the loop then.  But that's not quite the case. Try this and look at the output. It's only instantiating the variable on the first pass. Works the same on table variables, which is what I was actually curious about...