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:
Result:- DECLARE @EmpID VARCHAR(5)
- SET @EmpID = '123'
- SET @EmpID = (SELECT [EmpID]
- FROM [dbo].[Employee]
- WHERE [EmpID] = '321')
- --Assume that there is no record with empid 321 in employee table
- SELECT @EmpID
- Result:
- NULL
NULL
- If assigning a value using SET returns more than one value, SET will give an error.
Example:Result:- DECLARE @EmpName VARCHAR(50)
- SET @EmpName = 'Raj'
- SET @EmpName = (SELECT [EmpName]
- FROM [dbo].[Employee]
- WHERE [EmpName] = 'Tej')
- --Assume that there is multiple records with empname Tej in employee table
- SELECT @EmpName
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:
Result:- DECLARE @EmpID VARCHAR(5)
- SET @EmpID = '123'
- SELECT @EmpID = [EmpID]
- FROM [dbo].[Employee]
- WHERE [EmpID] = '321'
- --Assume that there is no record with empid 321 in employee table
- SELECT @EmpID
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:
Result:- DECLARE @EmpName VARCHAR(50)
- SET @EmpName = 'Raj'
- SELECT @EmpName = [EmpName]
- FROM [dbo].[Employee]
- WHERE [EmpName] = 'Tej'
- --Assume that there is multiple records with empname Tej in employee table
- SELECT @EmpName
Tej
Hari ShankerPosted Apr 20, 2016, 12:06 AM
nice
Teddy KurianPosted Jul 16, 2015, 7:53 AM
Good
benn rootPosted Jul 14, 2015, 6:37 AM
thanks... its useful....