There are 2 ways of assigning a value to a variable, they are SET and the SELECT statements.
SET
- By using SET, we can only assign one variable at a time.
Example:
- DECLARE @COUNT INT
- DECLARE @INDEX INT
-
- SET @COUNT=1
- SET @INDEX=2
- If assigning a value using SET from a query returns no result, then SET will assign a NULL value to the variable.
Example:
- DECLARE @EmpID VARCHAR(5)
- SET @EmpID = '123'
- SET @EmpID = (SELECT [EmpID]
- FROM [dbo].[Employee]
- WHERE [EmpID] = '321')
-
- SELECT @EmpID
-
- Result:
- NULL
Result:
NULL
- If assigning a value using SET returns more than one value, SET will give an error.
Example:
- DECLARE @EmpName VARCHAR(50)
- SET @EmpName = 'Raj'
- SET @EmpName = (SELECT [EmpName]
- FROM [dbo].[Employee]
- WHERE [EmpName] = 'Tej')
-
- SELECT @EmpName
Result:
Msg 512, Level 16, State 1, Line 3
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
SELECT
- By using SELECT we can assign values to more than one variable at a time.
Example:
- DECLARE @COUNT INT
- DECLARE @INDEX INT
-
- SELECT @COUNT=1 , @INDEX=2
- When assigning a value using SELECT from a query and the query returns no result, SELECT will not assign any value to the variable and therefore no change in the value of the variable.
Example:
- DECLARE @EmpID VARCHAR(5)
- SET @EmpID = '123'
- SELECT @EmpID = [EmpID]
- FROM [dbo].[Employee]
- WHERE [EmpID] = '321'
-
- SELECT @EmpID
Result:
10. 123
- When assigning a value using SELECT from a query that returns more than one value, SELECT will assign the last value returned by the query.
Example:
- DECLARE @EmpName VARCHAR(50)
- SET @EmpName = 'Raj'
- SELECT @EmpName = [EmpName]
- FROM [dbo].[Employee]
- WHERE [EmpName] = 'Tej'
-
- SELECT @EmpName
Result:
Tej