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 开发者_JAVA技巧my variable based on this column?
[othercolumn]
FROM
[exporttestresultreport] e
WHERE
[exporttestresultreportid] = @exporttestresultreportid
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?
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
精彩评论