2014-11-24 22 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