如何将标识值传递给UPDATE的out参数?

时间:2016-04-01 02:10:54

标签: sql-server

到目前为止,我有以下内容。

但是我不确定当我执行UPDATE时该怎么做 - 从另一个问题我发现你需要将OUTPUT INSERTED结果存储到表中,因为更新(或插入)可能会影响多行?我尝试使用SCOPE IDENTITY但它在UPDATE上返回NULL。无论如何,如果我使用表 - 那么如何获得一个可以传递给out参数的单个整数?或者我是否将out参数更改为其他类型,如集合?

ALTER PROCEDURE [Data].[UpdateRecord] 

@theValue decimal(4,2) = NULL, 
@updatetime datetimeoffset(7), 
@maxintervaltime datetimeoffset(7),
@recordID int = NULL output

AS

declare @mytable as TABLE
(
    Id int
)

begin tran
if exists (select * from Data.theValue with (updlock,serializable) where Data.theValue.maxintervaltime = @maxintervaltime)
begin
    update Data.theValue set theValue = @theValue, updatetime = @updatetime, maxintervaltime = @maxintervaltime
    where Data.theValue.maxintervaltime = @maxintervaltime
    -- OUTPUT INSERTED.id into @mytable (this line is wrong)
end
else
begin
    insert into Data.theValue(theValue, updatetime, maxintervaltime) values(@theValue, @updatetime, @maxintervaltime);
    SET @recordID = SCOPE_IDENTITY();
end

commit tran

1 个答案:

答案 0 :(得分:1)

输出子句应放在update和from / where子句之间。 UPDATE会影响多行,因此您必须确保逻辑正确。

update Data.theValue set theValue = @theValue, updatetime = @updatetime, maxintervaltime = @maxintervaltime
 OUTPUT INSERTED.id into @mytable 
where Data.theValue.maxintervaltime = @maxintervaltime

SET @recordID = top 1 id from @mytable