T-SQL is not only a query language. It also has features common in procedural programming languages. One of the most powerful capabilities of T-SQL is the ability for us to create and use variables.

Variable declaration

A variable represents a named object that holds some value. Variables are defined using the DECLARE statement, followed by the name and type of the variable. A variable’s name must begin with the @ symbol:

DECLARE @VariableName VariableType

It is also common among developers to use the AS keyword when indicating the variable’s type. However, there is no functional difference:

DECLARE @VariableName AS VariableType

Let’s create a variable called @StudentName:


Assigning values

There are two ways we can assign a value to a variable:

  • By using the SET keyword:

    SET @StudentName = 'Aidil'
  • By using the SELECT keyword:

    SELECT @StudentNAme = 'Aidil'

Print a variable value

Declaring a variable and assigning it a value is not useful if we cannot see what value this variable is currently holding. To print out the variable contents, we can use the PRINT keyword, which is used to print to the output. Let’s create a variable called @StudentName and print its contents:

Get hands-on with 1200+ tech skills courses.