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!
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.
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.
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.
SELECT
SELECT @ModelID = m.modelid FROM MODELS m WHERE m.areaid = 'South Coast'
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.
If this SELECT
statement returns multiple values (bad to begin with):
SELECT
, the variable is assigned the last value that is returned (as womp said), without any error or warning (this may cause logic bugs)SET
, an error will occurIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With