Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set variable from a SQL query?

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!

like image 912
Mr Cricket Avatar asked Oct 20 '10 04:10

Mr Cricket


People also ask

How do you DECLARE a variable in a SELECT statement?

SELECT @local_variable is typically used to return a single value into the variable. However, when expression is the name of a column, it can return multiple values. If the SELECT statement returns more than one value, the variable is assigned the last value that is returned.

Which keyword is used when assigning a variable from a query?

In below snapshot, SELECT statement is used to assign value to a variable from a select query. The SELECT statement assigns last value from the result set to the variable if the select query returns more than one result set.

How do you assign a row to a variable in SQL?

A row value can be assigned to a variable of type row by using a SELECT INTO statement, a VALUES INTO statement, or a FETCH INTO statement. The field values of the source row value must be assignable to the field values of the target row variable.


1 Answers

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
like image 183
OMG Ponies Avatar answered Sep 21 '22 23:09

OMG Ponies