Both SET and SELECT clauses can be used to assign values to the variables. While SET works for a single variable, SELECT works for more than a variable. If you want to assign values to multiple variables in single shot, SELECT can be used.
SELECT serves two perposes for variables
1 Assign values to variables
2 Return values from variables
Consider the following set of data
create table #t(id int, names varchar(100))
insert into #t(id,names)
select 1,'test1' union all
select 2,'test2' union all
select 3,'test3' union all
select 4,'test4' union all
select 5,'test5'
Suppose you want to find an id for the name test1 and assign it to a variable. You can use the following methods
declare @id int
set @id=(select id from #t where names='test1')
select @id as id
select @id=id from #t where names='test1'
select @id as id
Both SET and SELECT return the following result
id
-----------
1
Now see what happens when you forgot to specify the WHERE condition.
Using SET
declare @id int
set @id=(select id from #t)
select @id as id
returns the following error
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.
id
-----------
NULL
Using SELECT
declare @id int
select @id=id from #t
select @id as id
returns the following result
id
-----------
5
As you see the SELECT statement returns multiple ids which SET rejects it and throws an error message and
old value is retained for the variable (in the above example it is NULL). The SELECT will not throw an error message but it will assign the value available
last in the resultset (However there is no gaurantee if it is last. It changes when you use
ORDER BY Clause).
So always make sure that the SELECT query returns single value when you write code that assigns value to a variable. Otherwsie the variable will have wrong/unexpected data.