我想将这两个触发器组合成单个触发器。如何做到这一点

时间:2014-03-19 06:21:59

标签: sql-server

触发器1:

CREATE TRIGGER [dbo].[INSERT_IM_ServiceRequest_Hx] ON [dbo].[IM_ServiceRequest] AFTER INSERT
AS

BEGIN

INSERT INTO  IM_ServiceRequest_Hx
SELECT * FROM INSERTED


PRINT 'AFTER INSERT Trigger fired.'
END

触发器2:

CREATE TRIGGER [dbo].[UPDATE_IM_ServiceRequest] ON [dbo].[IM_ServiceRequest] FOR UPDATE
AS

BEGIN

INSERT INTO IM_ServiceRequest_Hx

SELECT * FROM DELETED

PRINT 'FOR UPDATE Trigger fired.'
END

1 个答案:

答案 0 :(得分:1)

您可以通过在CREATE TRIGGER声明中指定由逗号分隔的多个操作来组合它们。然后,使用适当的条件过滤器来决定如何更新审计表,如下所示:

CREATE TRIGGER [dbo].[INSERT_UPDATE_IM_ServiceRequest_Hx] ON [dbo].[IM_ServiceRequest] FOR INSERT, UPDATE
AS

BEGIN

IF EXISTS (SELECT * FROM INSERTED) AND NOT EXISTS (SELECT * FROM DELETED)
    BEGIN
    INSERT INTO  IM_ServiceRequest_Hx
    SELECT * FROM INSERTED

    PRINT 'AFTER INSERT Trigger fired.'
    END


IF EXISTS (SELECT * FROM INSERTED) AND EXISTS (SELECT * FROM DELETED)
    BEGIN
    INSERT INTO  IM_ServiceRequest_Hx
    SELECT * FROM DELETED

    PRINT 'FOR UPDATE Trigger fired.'
    END

END