This is my sql code –
declare @maxprice int --1
set @maxprice = 1000 --2
select @maxprice --3
I can execute these combinations 1,2 and 1,2,3 without errors. But, when I execute 1,2 first and 3 later, i get the error i mentioned.
I am not able to understand why this happens. Shouldn’t the select @maxprice be similar to a regular select statement ?
SQL statements like these are executed in as a block, and commands and definitions are only valid within the block. As soon as the block is finished, any declared variables go out of scope, and are undefined.
So, when you execute just line 3, SQL server does not know or check if you have previously done something with the same variable, and naturally complains that the variable is not defined.
If this was not so, and once declared variables remained in scope (e.g. for the duration of the session), the system would have to take great care to resolve clashes between, for example,
@maxpricebeing declare with aintin one procedure, and with amoneytype in another.A more detailed discussion of variables and scoping rules in SQL Server, can be found here.