SQL – Setting the Value of Variables inside server scripts.

Using SELECT:

SELECT @ModelID = m.modelid 
  FROM MODELS m
 WHERE m.areaid = 'South Coast'

Using SET:

SET @ModelID = (SELECT m.modelid 
                  FROM MODELS m
                 WHERE m.areaid = 'South Coast')

See this question for the difference between using SELECT and SET in TSQL.

Warning

If this select statement returns multiple values (bad to begin with):

  • When using SELECT, the variable is assigned the last value that is returned (as womp said), without any error or warning (this may cause logic bugs)
  • When using SET, an error will occur
shareimprove this answer

 

Resources: https://stackoverflow.com/questions/3974683/how-to-set-variable-from-a-sql-query