How to set variable from a SQL query?

前端 未结 9 1378
被撕碎了的回忆
被撕碎了的回忆 2020-11-28 01:19

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

declare @ModelID uniqueidentifer

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


        
相关标签:
9条回答
  • 2020-11-28 01:28

    Use TOP 1 if the query returns multiple rows.

    SELECT TOP 1 @ModelID = m.modelid 
      FROM MODELS m
     WHERE m.areaid = 'South Coast'
    
    0 讨论(0)
  • 2020-11-28 01:29

    I prefer just setting it from the declare statement

    DECLARE @ModelID uniqueidentifer = (SELECT modelid 
                                        FROM models
                                        WHERE areaid = 'South Coast')
    
    0 讨论(0)
  • 2020-11-28 01:31
    declare @ModelID uniqueidentifer
    
    --make sure to use brackets
    set @ModelID = (select modelid from models
    where areaid = 'South Coast')
    
    select @ModelID
    
    0 讨论(0)
  • 2020-11-28 01:41
    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

    0 讨论(0)
  • 2020-11-28 01:42

    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
    0 讨论(0)
  • 2020-11-28 01:42

    You can use this, but remember that your query gives 1 result, multiple results will throw the exception.

    declare @ModelID uniqueidentifer
    Set @ModelID = (select Top(1) modelid from models where areaid = 'South Coast')
    

    Another way:

    Select Top(1)@ModelID = modelid from models where areaid = 'South Coast'
    
    0 讨论(0)
提交回复
热议问题