Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to identify the operation type(insert,update,delete) in SQL Server trigger

We are using the following trigger in SQL Server to maintain the history now I need to identify the operations just like insert,update or delete. I found some information HERE but it doesn't works with the SQL Server.

CREATE TRIGGER audit_guest_details ON [PMS].[GSDTLTBL] 
FOR INSERT,UPDATE,DELETE
AS
    DECLARE @SRLNUB1 INT;
    DECLARE @UPDFLG1 DECIMAL(3,0);

    SELECT @SRLNUB1 = I.SRLNUB FROM inserted I;
    SELECT @UPDFLG1 = I.UPDFLG FROM inserted I;   

    BEGIN
       /* Here I need to identify the operation and insert the operation type in the GUEST_ADT 3rd field */
       insert into dbo.GUEST_ADT values(@SRLNUB1,@UPDFLG1,?);

       PRINT 'BEFORE INSERT trigger fired.'
    END;
GO

But here I need to identify the operation and want to insert operation type accordingly.

Here I don't want to create three trigger for every operations

like image 987
Gopal00005 Avatar asked Sep 25 '14 07:09

Gopal00005


2 Answers

For Inserted : Rows are in inserted only. For Updated: Rows are in inserted and deleted. For Deleted: Rows are in deleted only.

DECLARE @event_type varchar(42)
IF EXISTS(SELECT * FROM inserted)
  IF EXISTS(SELECT * FROM deleted)
    SELECT @event_type = 'update'
ELSE
    SELECT @event_type = 'insert'
ELSE
  IF EXISTS(SELECT * FROM deleted)
    SELECT @event_type = 'delete'
  ELSE
    --no rows affected - cannot determine event
    SELECT @event_type = 'unknown'
like image 177
Mikhail Timofeev Avatar answered Oct 20 '22 00:10

Mikhail Timofeev


This is a simplified version of Mikhail's answer that uses a searched CASE expression.

DECLARE @Operation varchar(7) = 
    CASE WHEN EXISTS(SELECT * FROM inserted) AND EXISTS(SELECT * FROM deleted) 
        THEN 'Update'
    WHEN EXISTS(SELECT * FROM inserted) 
        THEN 'Insert'
    WHEN EXISTS(SELECT * FROM deleted)
        THEN 'Delete'
    ELSE 
        NULL --Unknown
    END;
like image 42
Stephen Turner Avatar answered Oct 20 '22 01:10

Stephen Turner