Search code examples
sql-server-2008selectinsertdeclare

store SQL variable from INSERT query FROM clause result column


This is probably trivial to most of you, but I haven't been writing stored procedures for very long (6 months only). I'd like to be able to set the variable @testid based on one of the columns being used for an INSERT query. How can I do this?

DECLARE @testid INT;

INSERT INTO [exporttestresultreport] (
    [testid],
    [othercolumn]
) 
SELECT
    [testid],  -- <======= how can I set my variable based on this column?
    [othercolumn]
FROM 
    [exporttestresultreport] e
WHERE 
    [exporttestresultreportid] = @exporttestresultreportid

Solution

  • DECLARE @testid INT;
    
    DECLARE @test TABLE (testid int);
    
    INSERT INTO [exporttestresultreport] (
        [testid],
        [othercolumn]
    ) 
    OUTPUT INSERTED.testID INTO @test
    SELECT
        [testid],  -- <======= how can I set my variable based on this column?
        [othercolumn]
    FROM 
        [exporttestresultreport] e
    WHERE 
        [exporttestresultreportid] = @exporttestresultreportid;
    
    SELECT @testid = testid FROM @test;
    

    An INSERT..SELECT.. is inherently multirow so it doesn't make semse to allow assigning a value to a scalar variable: what row should be used for the value?