Tech Junkie Blog - Real World Tutorials, Happy Coding!: SQL Server : T-SQL Basics: Variables

Tuesday, March 17, 2015

SQL Server : 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

1 comment:

Search This Blog