Learn how to declare variables in SQL Server (Transact-SQL) with syntax and examples.
In SQL Server (Transact-SQL), a variable allows a programmer to store data temporarily during the execution of code.
The syntax to declare variables in SQL Server using the DECLARE statement is:
The name to assign to the variable.
The datatype to assign to the variable.
Optional. It is the value initially assigned to the variable when it is declared.
Let's look at an example of how to declare a variable in SQL Server.
For example:
This DECLARE statement example would declare a variable called @AODBA that is a VARCHAR datatype, with a length of 50 characters.
You then change the value of the @AODBA variable using the SET statement, as follows:
Next, let's also look at how to declare an INT variable in SQL Server.
For example:
To assign a value to the @site_value variable, you can use the SET statement, as follows:
This SET statement would assign the variable @site_value to the integer 10.
Let's look at how to declare more than one variable at a time in SQL Server.
For example:
In this example, we are declaring two variables. The first is the variable called @AODBA which is defined as a VARCHAR(50) and the second is a variable called @site_value which is declared as an INT.
Next, let's look at an example of how to declare a variable in SQL Server and give it an initial value.
For example:
This DECLARE statement example would declare a variable called @AODBA that is a VARCHAR datatype with a length of 50 characters. It would then set the variable of the @AODBA variable to 'Example showing how to declare variable'.
Finally, let's look at how to declare an INT variable in SQL Server and assign an inital value.
For example:
This variable declaration example would declare a variable called @site_value that is an INT datatype. It would then set the value of the @AODBA variable to the integer value fo 10.
Let's look at how to declare more than one variable and assign initial values to those variables in SQL Server.
For example:
In this example, we are declaring two variables and both of these variables are assigned initial values in their declaration.