SELECT @local_variable (Transact-SQL)
Applies To: SQL Server 2014, SQL Server 2016 Preview
Topic Status: Some information in this topic is preview and subject to change in future releases. Preview information describes new features or changes to existing features in Microsoft SQL Server 2016 Community Technology Preview 2 (CTP2).
Specifies that the specified local variable that is created by using DECLARE @local_variable should be set to the specified expression.
For assigning variables, we recommend that you use SET @local_variable instead of SELECT @local_variable. For more information, see SET @local_variable.
Applies to: SQL Server (SQL Server 2008 through current version), Azure SQL Database.
SELECT @local_variable is typically used to return a single value into the variable. However, when expression is the name of a column, it can return multiple values. If the SELECT statement returns more than one value, the variable is assigned the last value that is returned.
If the SELECT statement returns no rows, the variable retains its present value. If expression is a scalar subquery that returns no value, the variable is set to NULL.
One SELECT statement can initialize multiple local variables.
A SELECT statement that contains a variable assignment cannot be used to also perform typical result set retrieval operations.
A. Using SELECT @local_variable to return a single value
In the following example, the variable @var1 is assigned Generic Name as its value. The query against the Store table returns no rows because the value specified for CustomerID does not exist in the table. The variable retains the Generic Name value.
USE AdventureWorks2012 ; GO DECLARE @var1 nvarchar(30); SELECT @var1 = 'Generic Name'; SELECT @var1 = Name FROM Sales.Store WHERE CustomerID = 1000 ; SELECT @var1 AS 'Company Name';
Here is the result set.
B. Using SELECT @local_variable to no result set returns null
In the following example, a subquery is used to assign a value to @var1. Because the value requested for CustomerID does not exist, the subquery returns no value and the variable is set to NULL.
USE AdventureWorks2012 ; GO DECLARE @var1 nvarchar(30) SELECT @var1 = 'Generic Name' SELECT @var1 = (SELECT Name FROM Sales.Store WHERE CustomerID = 1000) SELECT @var1 AS 'Company Name' ;
Here is the result set.