How to set variable from a SQL query?

前端 未结 9 1419
被撕碎了的回忆
被撕碎了的回忆 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:48

    There are three approaches:

    1. DECLARE
    2. SET -- Microsoft Recommended approach
    3. SELECT

    Below query details the advantage and disadvantage of each:

    -- First way, 
    DECLARE @test int = (SELECT 1)
           , @test2 int = (SELECT a from (values (1),(2)) t(a)) -- throws error
    
    -- advantage: declare and set in the same place
    -- Disadvantage: can be used only during declaration. cannot be used later
    
    -- Second way
    DECLARE @test int  
           , @test2 int 
    
    SET @test = (select 1)
    SET @test2 = (SELECT a from (values (1),(2)) t(a)) -- throws error
    
    -- Advantage: ANSI standard. 
    -- Disadvantage: cannot set more than one variable at a time
    
    -- Third way
    DECLARE @test int, @test2 int 
    SELECT @test = (select 1)
          ,@test2 = (SELECT a from (values (1),(2)) t(a)) -- throws error
    
    -- Advantage: Can set more than one variable at a time
    -- Disadvantage: Not ANSI standard
    

提交回复
热议问题