触发器处理多行插入和更新

时间:2016-07-07 19:23:00

标签: sql-server triggers

我使用以下触发器来跟踪多个表的插入和更新,并将其记录在日志表中。

CREATE TRIGGER tr_TestTable1]
ON [TestTable_1]
AFTER INSERT, UPDATE
AS
DECLARE @keyid int, @tn nvarchar(50), @recEditMode nvarchar(50), @trstat nvarchar(50)
BEGIN
    SET NOCOUNT ON;   
    SET @tn = 'TestTable_1'
    IF EXISTS(SELECT 1 FROM INSERTED)
    BEGIN
    SET @recEditMode = (Select REC_EDIT_MODE FROM inserted)
    SET @trstat = 'PENDING'
    SET @keyid = (Select prkeyId FROM inserted)

    IF (@recEditMode = 'MANUAL')
    BEGIN
    IF NOT EXISTS (SELECT * FROM [logTable_1] WHERE SourceKeyId = @keyid AND TrStatus = 'PENDING' AND SourceTableName = @tn)
        BEGIN
            INSERT INTO [logTable_1](SourceKeyId,SourceTableName,TrStatus)
                VALUES (@keyid, @tn, @trstat)       
        END
    END
        END

END

这适用于单行插入和单行更新。我无法优化此代码来处理多行插入和更新。寻求一些帮助来处理这个。

感谢。

1 个答案:

答案 0 :(得分:0)

我修改了触发器,如下所示,现在看起来工作正常......

 CREATE TRIGGER tr_TestTable1]
    ON [TestTable_1]
    AFTER INSERT, UPDATE
    AS
    DECLARE @keyid int, @tn nvarchar(50), @trstat nvarchar(50)
    BEGIN
        IF @@ROWCOUNT = 0 
        RETURN
        SET NOCOUNT ON;   
        IF EXISTS(SELECT * FROM INSERTED)
        BEGIN
        SET @tn = 'TestTable_1'
        SET @trstat = 'PENDING'
        BEGIN
        INSERT INTO LogTable_1 (SourceKeyId, SourceTableName, TrStatus)
        SELECT I.prKeyId, @tn, @trStat FROM INSERTED AS I
        WHERE (I.REC_EDIT_MODE = 'MANUAL' AND NOT EXISTS(SELECT * FROM LogTable_1 WHERE SourceKeyId =   I.prKeyId AND SourceTableName = @tn AND TrStatus = 'PENDING'))

        END
    END
END