Wednesday, 18 December 2013

T-SQL - Local Variables

Local Variables 

Variables are used to store the values so that these values can be used later.

Syntax

Declaration:   DECLARE @Variable_name Data_type;
Initilization:  SET @Variable_name = value;

For later versions of SQL Server  2005, we can declare and set the value of variables in single line.
 e.g. DECLARE My_Variable int =10;
Scope

Scope of the local variables is between the declaration of the variable and the end of the current batch.

Example 1


Example 2

 
Example 3


 

Example 4
Declare a variable in a query window and try to select it in another query window you will get an error. This is because of scope of local variable.