Why is variable declared inside IF statement creat

2019-01-20 07:34发布

问题:

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

thanx

回答1:

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.



回答2:

gbn's answered the question, but on a related note, watch out for code like this :

DECLARE @i INT = 0
WHILE @i < 2
BEGIN
    DECLARE @a VARCHAR(100)

    IF @i = 0
        SET @a = 'changed'

    PRINT COALESCE(@a, 'is null')   
    SET @i = @i + 1
END

When run, it prints "changed" twice, whereas many people would probably expect it to print "changed", then "is null". Be careful when declaring variables inside loops. You might want to explicitly set it to NULL in the declaration. e.g.

DECLARE @a VARCHAR(100) = NULL

When this modified version is run, it displays "changed" then "is null".