如何将 OUTPUT DELETED 的结果分配给输出参数?

How to assign result of OUTPUT DELETED to an output parameter?

我有以下生成下一个可用提单编号的查询。

ALTER PROCEDURE [dbo].[GetNextTruckBol]
    @FacilityId INT,
    @Count INT = 1
AS
BEGIN
    SET NOCOUNT ON;
    UPDATE Facilities
    SET NextTruckBol = NextTruckBol + @Count
    OUTPUT DELETED.NextTruckBol
    WHERE Id = @FacilityId
END

但现在我需要修改它,以便将结果值分配给 OUTPUT 参数。

我知道如何声明 OUTPUT 参数。如何将 OUTPUT DELETED.NextTruckBol 的值分配给该参数?

根据 UPDATE 文档

Variable names can be used in UPDATE statements to show the old and new values affected, but this should be used only when the UPDATE statement affects a single record. If the UPDATE statement affects multiple records, to return the old and new values for each record, use the OUTPUT clause.

因此,如果您知道 UPDATE 只会影响最多一行(因为 Id 被限制为唯一)并且您不想弄乱 table您可以使用的变量

SET @variable = column, column = expression, which sets the variable to the pre-update value of the column.

那就是

CREATE OR ALTER PROCEDURE [dbo].[GetNextTruckBol]
    @FacilityId INT,
    @Count INT = 1,
    @NextTruckBol INT OUTPUT
AS
BEGIN
    SET NOCOUNT ON;

    UPDATE Facilities
    SET @NextTruckBol = NextTruckBol,
        NextTruckBol = NextTruckBol + @Count
    WHERE Id = @FacilityId
END