为多个操作创建一个触发器

时间:2014-11-24 08:01:40

标签: sql-server-2008 triggers

我的问题是,我可以在一个表上为多个操作(插入/更新/删除)创建一个触发器吗?像这样:

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 个答案:

答案 0 :(得分: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