views:

92

answers:

3

What are the differences between SET vs. SELECT statement when assigning variables in T-SQL?

A: 

With SELECT you can perform multiple assignments at once. With SET you are limited to one. As far as I've ever been told, this is the only difference.

Brad
+10  A: 

Quote, which summarizes from this article:

  1. SET is the ANSI standard for variable assignment, SELECT is not.
  2. SET can only assign one variable at a time, SELECT can make multiple assignments at once.
  3. If assigning from a query, SET can only assign a scalar value. If the query returns multiple values/rows then SET will raise an error. SELECT will assign one of the values to the variable and hide the fact that multiple values were returned (so you'd likely never know why something was going wrong elsewhere - have fun troubleshooting that one)
  4. When assigning from a query if there is no value returned then SET will assign NULL, where SELECT will not make the assignment at all (so the variable will not be changed from it's previous value)
  5. As far as speed differences - there are no direct differences between SET and SELECT. However SELECT's ability to make multiple assignments in one shot does give it a slight speed advantage over SET.
OMG Ponies
+1 for learning me something :)
Brad
OMG Ponies
Concise and comprehensive...
gbn
I did not downvote, but the following is not quite correct: "As far as speed differences - there are no direct differences between SET and SELECT". If you assign multiple values in one slect, that can be much faster that via maultiple sets. Google up "Assigning multiple variables with one SELECT works faster"
AlexKuznetsov
@AlexKuznetsov: The sentence afterwards says exactly that.
OMG Ponies
@OMG Ponies: It can be 10 times faster or more, so I am not sure if it is "slight speed advantage".
AlexKuznetsov
+1  A: 

I believe SET is ANSI standard whereas the SELECT is not. Also note the different behavior of SET vs. SELECT in the example below when a value is not found.

declare @var varchar(20)
set @var = 'Joe'
set @var = (select name from master.sys.tables where name = 'qwerty')
select @var /* @var is now NULL */

set @var = 'Joe'
select @var = name from master.sys.tables where name = 'qwerty'
select @var /* @var is still equal to 'Joe' */
Joe Stefanelli
+1 It is better to run once in order to understand, check, play, memorize that to just read but other answers are just text
vgv8