sqlsql-servert-sql

Why is a variable declared inside IF statement created even when the condition evaluates to false?


Since @A is never declared, SQL Server should throw an error, but it doesn't. Why is that?

DECLARE @i int = 1;
IF @i > 10
BEGIN
  DECLARE @A int = 100;
END

PRINT @A; -- Doesn't return any result

Solution

  • SQL Server does not have block level variable scoping.

    It's per batch/stored proc etc

    From MSDN (my bold)

    The scope of a variable is the range of Transact-SQL statements that can reference the variable. The scope of a variable lasts from the point it is declared until the end of the batch or stored procedure in which it is declared.