views:

61

answers:

2

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

+7  A: 

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.

gbn
Makes sense, but isn't this a flaw of sort, since perhaps there are situations where we'd like to create a variable only when certain conditions are met?
AspOnMyNet
Not really. SQL is not compiled or scoped like c#, say, because it's declarative. As a developer DBA, I could say c# and Java are flawed because of their scoping rules, with variables declared in outer and inner blocks. I mean, having 2 @A vars? C'mon...
gbn
thanx for helping me
AspOnMyNet
+1  A: 

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

Moe Sisko
Good advice.I'd probably missed that one. Thanx
AspOnMyNet