【问题标题】:store SQL variable from INSERT query FROM clause result column从 INSERT 查询 FROM 子句结果列存储 SQL 变量
【发布时间】:2011-10-18 12:33:40
【问题描述】:

这对你们大多数人来说可能是微不足道的,但我已经很久没有编写存储过程了(仅 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

【问题讨论】:

    标签: sql-server-2008 select insert declare


    【解决方案1】:
    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.. 本质上是多行的,因此它不允许将值分配给标量变量:应该使用哪一行作为值?

    【讨论】:

    • 如果您更正语法,我会将其标记为答案。这就是我选择其他人的原因。如何组合这些查询?
    【解决方案2】:
    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
    

    【讨论】:

    • 你知道如何在同一个 OUTPUT 行中添加多个临时表吗?
    • 当然,您可以向 @t 添加更多列,然后将 , INSERTED.othercolumn 添加到 OUTPUT 子句。但是,如果您的意图是将所有列输出到变量中,那么为什么不只是 SELECT @testid = testid, @othercolumn = othercolumn FROM ...; INSERT exporttestresultreport SELECT @testid, @othercolumn;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-29
    • 2012-03-13
    • 2016-06-21
    • 1970-01-01
    • 1970-01-01
    • 2020-03-03
    • 2019-12-29
    相关资源
    最近更新 更多