开发者

store SQL variable from INSERT query FROM clause result column

开发者 https://www.devze.com 2023-03-24 12:30 出处:网络
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

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
0

精彩评论

暂无评论...
验证码 换一张
取 消