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...




DECLARE @i INT

SET @i = 0
SET nocount ON

WHILE @i < 5
  BEGIN
      DECLARE @temp TABLE
        (
           f1 INT IDENTITY,
           f2 VARCHAR(10)
        )
      DECLARE @c VARCHAR(100)

      SET @c = Isnull(@c, '') + 'yay!'

      INSERT INTO @temp
                  (f2)
      VALUES     ( 'hi' )

      SELECT *
      FROM   @temp t

      PRINT @c

      PRINT Char(13)

      SET @i = @i + 1
  END 



Comments

Popular posts from this blog

SOPA and the NDAA

Hiding an ASPXGridView Delete button with HTMLRowCreated vs. CommandButtonInitialize

Why I still don't use Entity Framework for small-to-medium business applications