SQLServer assigns values to defined variables in two ways: SET and SELECT. The difference between the two methods has been described in detail in SQLServer books online. However, we do not pay attention to the fact that there are many differences between the two methods.
SQLServer assigns values to defined variables in two ways: SET and SELECT. The difference between the two methods has been described in detail in the SQL Server online series, but we do not pay attention to the fact that there are many differences between the two methods.
SET instead of SELECT is recommended for SQL Server.
When the expression returns a value and assigns a value to a variable, the SET method is recommended.
The following table lists the differences between SET and SELECT. Pay special attention to the red part.
The following is an 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 the expression returns multiple values, use SET to assign values.
Declare @ addr varchar (128)
Set @ addr = (select addr from chinadba1)
/*
-- The error message is
Server: message 512, level 16, status 1, row 2
The subquery returns more than one value. When the subquery follows in = ,! =, <, <=,>,> =, Or use a subquery as an expression.
*/
Go
When the expression returns multiple values, use SELECT to assign values to declare @ addr varchar (128)
Select @ addr = addr from chinadba1
Print @ addr -- value of the last addr column in the result set
-- Result: addr3
Go
When the expression does not return a value, use the SET value declare @ addr varchar (128)
Set @ addr = 'initiator'
Set @ addr = (select addr from chinadba1 where userid = 4)
Print @ addr -- null value
Go
If the expression does not return a value, use SELECT to assign values to declare @ addr varchar (128)
Set @ addr = 'initiator'
Select @ addr = addr from chinadba1 where userid = 4
Print @ addr -- keep original value
Go
Note that SELECT can also assign the value of the scalar quantum query to the variable. if the scalar query does not return a value, the variable is set to null.
In this case, it is exactly the same as using SET assignment.
The concept of Benchmarking quantum queries should be unfamiliar to everyone. for example, it can be explained.
Declare @ addr varchar (128)
Set @ addr = 'initiator'
-- Select addr from chinadba1 where userid = 4 is a scalar query statement.
Select @ addr = (select addr from chinadba1 where userid = 4)
Print @ addr -- null value
Go