SQL Server - INSERTED.OUTPUT - 变量赋值

时间:2014-02-15 15:06:36

标签: sql-server-2012

我正在做以下事情:

UPDATE dbo.Crash
SET NbrOfCrash = NbrOfCrash + 1  
OUTPUT INSERTED.NbrOfCrash
WHERE CrashId = 1

现在我想将此语句的OUTPUT分配给变量:

DECLARE @result int;

这可以吗?

由于

1 个答案:

答案 0 :(得分:2)

选项#1:您可以使用

UPDATE dbo.Crash
SET @result = NbrOfCrash = NbrOfCrash + 1  
WHERE CrashId = 1

仅当CrashId列上有pk /唯一键/唯一约束

选项#2:否则,您可以使用

declare @updated_rows table (
NbrOfCrash int -- replace int with proper type
);

UPDATE dbo.Crash
SET NbrOfCrash = NbrOfCrash + 1  
OUTPUT INSERTED.NbrOfCrash into @updated_rows
WHERE CrashId = 1;

select @result = NbrOfCrash / min(NbrOfCrash) / max(NbrOfCrash) / avg(NbrOfCrash) ...
from @updated_rows;