views:

75

answers:

2

Hi, I'm trying to set a variable from a SQL query:

declare @ModelID uniqueidentifer

Select @ModelID = select modelid from models
where areaid = 'South Coast'

Obviously I'm not doing this right as it doesn't work. Can somebody suggest a solution?

Thanks!

+4  A: 
SELECT @ModelID = modelid
FROM Models
WHERE areaid = 'South Coast'

If your select statement returns multiple values, your variable is assigned the last value that is returned.

For reference on using SELECT with variables: http://msdn.microsoft.com/en-us/library/aa259186%28SQL.80%29.aspx

womp
Thanks for the help! Had to be something simple.
Mr Cricket
+10  A: 

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
OMG Ponies
A complete answer.
Feil
+1 Nice answer X-)
astander
If this select statement returns multiple values: in the first case, the variable is assigned the last value that is returned (as womp said), without any error or warning (this may cause logic bugs); in the second case, an error will occur.
Feil
BTW, the case using SET needs a pair of brackets: SET @ModelID = (SELECT ...)
Feil
@Feil: Thx, hope you don't mind me quoting you.
OMG Ponies