SQL Server:在批量更新上触发

时间:2018-08-06 15:18:16

标签: sql tsql

如何更改下面的触发器以进行批量更新?在触发器中,我得到了传入的ActivityTypeID。如果值为“ 32E490BB-DA7E-E811-80D9-00155D012204”,则请确保将IsBillable列设置为0,否则将其设置为1。

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TRIGGER [dbo].[trg_WorklogInsert1]
ON  [dbo].[WorkLog]
AFTER INSERT, UPDATE
AS 
BEGIN
    SET NOCOUNT ON;

    DECLARE @ActivityTypeID UNIQUEIDENTIFIER;

    SET @ActivityTypeID = (SELECT [ActivityType_Id] FROM inserted);

    IF @ActivityTypeID = '32E490BB-DA7E-E811-80D9-00155D012204'
    BEGIN
        UPDATE w
        SET w.IsBillable = 0
        FROM [dbo].[WorkLog] AS w
        INNER JOIN inserted AS i ON w.Id = i.Id
    END
    ELSE
    BEGIN
        UPDATE w
        SET w.IsBillable = 1
        FROM [dbo].[WorkLog] AS w
        INNER JOIN inserted AS i ON w.Id = i.Id
    END
END

1 个答案:

答案 0 :(得分:2)

美好的一天,

请检查波纹管触发器是否满足您的需求:

CREATE TRIGGER [dbo].[trg_WorklogInsert1] ON  [dbo].[WorkLog] AFTER INSERT,UPDATE AS BEGIN
    SET NOCOUNT ON;
    UPDATE w
        set w.IsBillable = 
        CASE 
            WHEN i.ActivityType_Id = '32E490BB-DA7E-E811-80D9-00155D012204'
                THEN 0
            ELSE 1
        END
    FROM [dbo].[WorkLog] as w
    INNER JOIN inserted as i on w.Id = i.Id
END
GO

注意!据我了解,您的问题与批量插入无关,而是与一起插入的多行相关(您的触发器版本仅适用于您插入/更新单个行的情况行)。如果不是这种情况,请详细说明。