Category Archives: T-SQL Understanding the numerous types of
variable SQL Server has to offer, and their appropriate usage is
one of the cornerstones of developing effective database code. I
recently helped a co-worker fix an error message in his code. --
Error Msg 137, Level 15, State 2, Line 3 Must declare the scalar
variable "@l_INT". The code snippet looked something like this,
which led to a discussion about scope of T-SQL variables and an
interesting way to fix this problem. CREATE TABLE #scope_test1
(col1 INT); CREATE TABLE #scope_test2 (col1 INT); GO DECLARE
@l_INT INT = 42; INSERT INTO #scope_test1 (col1) SELECT @l_INT;
GO INSERT INTO #scope_test2 (col1) SELECT @l_INT; GO T-SQL
language supports local variables (their names begin with a
single @). 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. A T-SQL
batch is a group of