It’s always nice to learn something new…

Today I learned that variables in SQL Server stored procedures have no scope rules.

Take this example:

--
Declare @Outer int
Set @Outer = 1

While 1 = 1
begin
    Declare @Inner int
    Set @Inner = 2
    break
end
Select @Outer, @Inner

As a developer I expected that a new “instance” of @Inner would be created on each iteration of the loop and that the ending select would actually get an error saying that there was no variable @Inner.

But this is not true, all variables have a scope of the batch in which they are declared, code blocks be damned!

Lesson learned… re-initialized each loop of the procedure and everything works as expected.

Embarrassing as I’ve been writing stored procedures for 15 years…