SQL Server recommends assigning a variable using SET instead of SELECT.
The SET method is recommended when an expression returns a value and assigns a variable.
The following table lists the differences between SET and SELECT. Please pay special attention to the red section.
|
Set |
Select |
Assign values to multiple variables at the same time |
does not support |
Support |
When an expression returns multiple values |
Error |
Assigns the last value returned to a variable |
Expression does not return a value |
variable is assigned null value |
Variable keeps the original value |
Here's a concrete example to illustrate the problem:
CREATE TABLE Chinadba1 (
UserID int,
Addr varchar (128)
)
Go
Insert into CHINADBA1 (USERID,ADDR) VALUES (1, ' ADDR1 ')
Insert into CHINADBA1 (USERID,ADDR) VALUES (2, ' ADDR2 ')
Insert into CHINADBA1 (USERID,ADDR) VALUES (3, ' ADDR3 ')
Go
When an expression returns multiple values, the SET assignment is used
DECLARE @addr varchar (128)
Set @addr = (select addr from Chinadba1)
/*
--The error message is
Server: Message 512, Level 16, State 1, line 2
The subquery returns more than one value. This is not allowed when the subquery follows =,!=, <, <=, >, >=, or the subquery is used as an expression.
*/
Go
When an expression returns multiple values, declare @addr varchar (128) using the SELECT assignment.
Select @addr = addr from Chinadba1
Print @addr--the value of the last addr column in the result set
--Results: ADDR3
Go
When an expression does not return a value, the SET assignment declare @addr varchar (128)
Set @addr = ' initial value '
Set @addr = (select addr from chinadba1 where UserID = 4)
Print @addr--null value
Go
When the expression does not return a value, use SELECT to assign declare @addr varchar (128)
Set @addr = ' initial value '
Select @addr = addr from chinadba1 where UserID = 4
Print @addr--Keep the original value
Go
It should be noted that SELECT can also assign the value of a scalar quantum query to a variable, and if the scalar query does not return a value, the variable is set to a null value.
This is exactly the same as using the SET assignment.
The concept of the standard quantum query should all be unfamiliar, for example, we can explain
DECLARE @addr varchar (128)
Set @addr = ' initial value '
--select addr from chinadba1 where UserID = 4 for standard Quantum query statements
Select @addr = (select addr from chinadba1 where UserID = 4)
Print @addr--null value
Go