2014-03-19 41 views
0

觸發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

你可以通過指定用逗號分隔的多個動作將它們結合起來在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 
+0

當然,這是從原來的觸發器細微的差別在0行的情況下'INSERT'或'UPDATE' 。原始觸發器仍然是'PRINT'消息,但這個觸發器不會。可能無所謂,但值得強調。 –

+0

@Damien_The_Unbeliever我確實懷疑合併不會完全忠於OP的原始代碼,但不能指出它。你能幫我改進這個答案嗎?我真的很感激:) –

相關問題