CHAPTER 10
Programmable Objects
343
Batches and Variables
A variable is local to the batch in which it is defined. If you try to refer to a variable that was defined
in another batch, you will get an error saying that the variable was not defined. For example, the fol-
lowing code declares a variable and prints its content in one batch, and then tries to print its content
from another batch.
DECLARE @i AS INT;
SET @i = 10;
-- Succeeds
PRINT @i;
GO
-- Fails
PRINT @i;
The reference to the variable in the first PRINT statement is valid because it appears in the same
batch where the variable was declared, but the second reference is invalid. Therefore, the first PRINT
statement returns the variable’s value (10), whereas the second fails. Here’s the output returned from
this code.
10
Msg 137, Level 15, State 2, Line 3
Must declare the scalar variable "@i".
Do'stlaringiz bilan baham: |