Thursday, January 5, 2017

a simple trigger for SQL Server Update Insert and Delete action

i show a easy way to do data auditing with trigger on an Order Table, which will allow user to update and Insert records in the Order table.

here i implement a logic to determine the user action like Update or Insert, if a record is being delete and insert then we know the record had been update, otherwise it is a straight insert

  IF EXISTS(SELECT * FROM INSERTED) AND EXISTS(SELECT * FROM DELETED)
    begin
        set @Operation='Update'
    end
   else
   begin
        set @Operation='Insert'
    end


ALTER trigger [dbo].[tblTriggerInsertUpdateAuditRecord] on [dbo].[Order]
after update, insert
as
begin
  declare @Operation nvarchar(10)
  IF EXISTS(SELECT * FROM INSERTED) AND EXISTS(SELECT * FROM DELETED)
    begin
        set @Operation='Update'
    end
   else
   begin
        set @Operation='Insert'
    end
  insert into OrderAudit
  ( OrderID
      ,OrderNumber
      ,OrderDate
      ,ShipperID
      ,ShippingCompanyID
      ,WorkStationID
      ,PaymentTermID
      ,CreateDate
      --,UpdateDate
      ,OrderStatus
      ,IsTailGateRequire
      ,AdditionalOrders
      ,TotalPieces
      ,TotalWeight
      ,Supervisor
      ,Operation )
  select  i.OrderID
      ,i.OrderNumber
      ,i.OrderDate
      ,i.ShipperID
      ,i.ShippingCompanyID
      ,i.WorkStationID
      ,i.PaymentTermID
      ,GETDATE()
      ,i.OrderStatus
      ,i.IsTailGateRequire
      ,i.AdditionalOrders
      ,i.TotalPieces
      ,i.TotalWeight
      ,i.Supervisor
      ,@Operation
  from  Order t
  inner join inserted i on t.OrderID=i.OrderID
end













In term of delete, we just need to copy a record from delete table in Temp database

ALTER trigger [dbo].[triggerDeleteAuditOrderDetails] on [dbo].[OrderDetails]
after delete
as
begin
  insert into OrderDetailsAudit
    (OrderDetailsID
      ,SCIOrderID
      ,Quantities
      ,ShipItemID
      ,IsDangerousGoods
      ,DangerousGoodsHazardClassID
      ,Weight
      ,Operation
      ,CreateDate)
  select  D.OrderDetailsID
      ,D.SCIOrderID
      ,D.Quantities
      ,D.ShipItemID
      ,D.IsDangerousGoods
      ,D.DangerousGoodsHazardClassID
      ,D.Weight
      ,'Delete'
      ,GetDate()
  From DELETED
end




No comments:

Post a Comment