插入后更新另一个表的SQL触发器

时间:2018-12-21 09:05:47

标签: sql sql-server tsql triggers

我想在另一个表中完成插入后更新表中的实体。这是我目前无法使用的触发器。

ALTER TRIGGER [dbo].[UpdateLastValues]  
ON [dbo].[MeasureValues] FOR INSERT   
AS BEGIN

SET NOCOUNT ON;

DECLARE @MyValue AS nvarchar;
DECLARE @MyTimestamp AS datetimeoffset;
DECLARE @MyId AS nvarchar;

SELECT @MyValue = Value FROM INSERTED;
SELECT @MyTimestamp = Timestamp FROM INSERTED;
SELECT @MyId = MeasurePointId FROM INSERTED;

UPDATE [dbo].[MeasurePoints] SET  [dbo].[MeasurePoints].[LastValue] = @MyValue, [dbo].[MeasurePoints].[LastEdit] = @MyTimestamp WHERE [dbo].[MeasurePoints].[Id] = @MyId
END

度量值将接收新值。最新值应保存在MeasurePoints LastValue列中。

1 个答案:

答案 0 :(得分:4)

将触发器从FOR INSERT更改为AFTER INSERT

我还对代码进行了一些更改,以删除不必要的代码

ALTER TRIGGER [dbo].[UpdateLastValues]  
ON [dbo].[MeasureValues] AFTER INSERT   
AS BEGIN

SET NOCOUNT ON;

UPDATE MP
    SET
        LastValue = INSERTED.[Value],
        LastEdit = INSERTED.[Timestamp]
    FROM [dbo].[MeasurePoints] MP
        INNER JOIN Inserted
            ON MP.id = Inserted.MeasurePointId

END