T-SQL Basics: Variables















T-SQL variables allows you to store and assign values in your T-SQL code.  Variables is a storage unit in programming which allows you to refer back to it at a later time.

T-SQL variables have the following characteristics:
  • Local variables must be prefixed @
  • Global variables must be prefixed with @@
  • Must be declared with the DECLARE statement
  • Must specify the data type when declared
Declaring variables
    DECLARE @employeeID INT;
DECLARE @firstName CHAR(10), @lastName CHAR(20);

As you can see from the above example you can declare a single variable or declare multiple variables with a comma separated list.

Setting variables

  SET @employeeID = 1;
SET @firstName='Davolio';
SET @lastName='Nancy';

The above example uses the SET statement assign values to the variables one at a time.

To assign values to multiple variables with one statement you can use the SELECT statement.
SELECT @employeeID=1,@firstName='Dovolio',@lastName='Nancy';

Convert INT Variable To String
 
  Convert(CHAR,@employeeID);

Comments

Popular posts from this blog

Installing AdventureWorks Sample Databases from Microsoft

SQL: GROUP BY And HAVING

ASP.NET : Create an Empty Web Application Project in Visual Studio 2012