0

这对你们大多数人来说可能是微不足道的,但我已经很久没有编写存储过程了(仅 6 个月)。我希望能够根据用于 INSERT 查询的列之一设置变量 @testid。我怎样才能做到这一点?

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
4

2 回答 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;

INSERT..SELECT.. 本质上是多行的,因此它不允许将值分配给标量变量:应该使用哪一行作为值?

于 2011-08-02T18:52:17.137 回答
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
于 2011-08-02T18:56:55.890 回答