0

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

2 Answers 2

3
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?

Sign up to request clarification or add additional context in comments.

1 Comment

If you correct your syntax I will mark it as the answer. That's why I chose the other fella's. How can I combine those queries?
1
DECLARE @testid INT;

DECLARE @t TABLE(t INT);

INSERT exporttestresultreport
(
    testid, othercolumn
)
OUTPUT INSERTED.testid INTO @t
SELECT testid, othercolumn 
FROM 
    [exporttestresultreport] e
WHERE 
    [exporttestresultreportid] = @exporttestresultreportid;

SELECT @testid = t FROM @t;

-- not sure what you want to do if there are multiple rows in the insert

2 Comments

Do you know how I can add multiple temp tables in the same OUTPUT line?
Sure, you can add more columns to @t and then add , INSERTED.othercolumn to the OUTPUT clause. But if your intention is to output ALL of the columns into variables, then why not just SELECT @testid = testid, @othercolumn = othercolumn FROM ...; INSERT exporttestresultreport SELECT @testid, @othercolumn;?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.