1

My question is, can I create one trigger for multiple operations (insert/update/delete) on one table ? Something like this :

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 

Now I have to create 3 triggers for this task while I can combine them into one!

NeedAnswers
  • 1,411
  • 3
  • 19
  • 43

1 Answers1

1

Nevermind, I got it :

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
NeedAnswers
  • 1,411
  • 3
  • 19
  • 43