2014-11-24 47 views
1

我的問題是,我可以在一個表上創建多個操作(插入/更新/刪除)的一個觸發器嗎?事情是這樣的:爲多個操作創建一個觸發器

Create trigger [dbo].[TR_AUDIT_TESTAUDIT] 
    ON [dbo].[testaudit] 
    AFTER UPDATE, INSERT, DELETE 
    AS BEGIN 

    -- prepare the audit data 

    case the operation is insert then 
    case the operation is delete then 
    case the operation is update then 

    -- process auditdata 

    END 

現在我要創建3個觸發此任務的同時,我可以將它們合併成一個!

回答

1

沒關係,我懂了:

Create trigger [dbo].[TR_AUDIT_TESTAUDIT] 
    ON [dbo].[testaudit] 
    AFTER INSERT, UPDATE, DELETE 
    AS 
BEGIN 
    SET NOCOUNT ON; 
    declare @action nvarchar(1) 

    set @action = 'I' -- always I 

    if exists(select top 1 1 from deleted) and not exists(select top 1 1 from inserted)   
    set @action = 'D' 

    if exists(select top 1 1 from deleted) and exists(select top 1 1 from inserted)   
    set @action = 'U'   
END