Scope of table variable within SQL cursor
Solution 1:
Yes, it does - the scope isn't defined by the begin
/ end
statements, but by the end of a stored procedure, or a go
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.
http://msdn.microsoft.com/en-us/library/ms187953(v=sql.105).aspx
Solution 2:
Variable declarations in T-SQL are a bit of an odd beast - variable declarations ignore control flow.
This produces an error:
set @a = 2
This runs without issue, and doesn't print "Never":
if 1=0
begin
print 'Never'
declare @a int
end
set @a = 2
The lifetime of a variable is from the point of declaration until the batch completes.