A variable is a user-friendly name given to an area of memory that stores a value.
Variables are one of the most common elements of Transact-SQL programming.
Variables are useful in many situations. You will find yourself using them when:
Declaring parameters for stored procedures
Storing values used in calculations
Looping a specific number of times
You do not need to undeclare a variable, because the memory will be freed when the batch of Transact-SQL statements is finished.
The availability of your variable varies depending on whether you are using Transact-SQL or the Query Analyzer to process queries:
If you use the Query Analyzer to execute Transact-SQL statements, the variable will be available throughout all the Transact-SQL statements within the Query Analyzer window,
unless you have separated the code into batches with the
If you use Transact-SQL, your variable will be available for the duration of the batch in which it is created. Therefore, if you declare a variable within a stored procedure,
it is available everywhere within the stored procedure, but not to others.
The following Slide Show contains examples of declaring, assigning a value, and using a variable in Transact-SQL:
Microsoft SQLServer 2005
In the next lesson, functions within your Transact-SQL programming will be discussed.