Maybe my original post was little messy, so I didn't get much help. I updated my trigger with the AuditTest table.... Please see if you can help.
I am very new to triggers and trying to put together an audit table where it tracks the value changes on certain columns.
I have a lot of columns like: Qty, UnitSell, Discount, ProductName ...etc. This code below seems to work, which detects the Qty or UnitSell value changes, then do the INSERT INTO the audit table (now I just named it as TEST1)
If I would keep repeating the IF UPDATE(FieldName) statement for other columns, I think it will work, but it is too cumbersome in which keep repeating the same codes.
Is that way to optimize this, so I don't have to repeating the same IF UPDATE (Fieldname) statement?
alter TRIGGER trigger_Test_AfterUpdate
ON [dbo].ERP_QuoteDetail
FOR UPDATE
AS
declare @QuoteDetailID int;
select @QuoteDetailID = i.QuoteDetailID from inserted i;
--- Updating QTY if old/new value change
DECLARE @iQty int; SELECT @iQty = i.Qty from inserted i;
DECLARE @dQty int; SELECT @dQty = d.Qty from deleted d;
if update(QTY) and exists (select * from deleted d WHERE Qty <> @iQty)
BEGIN
-- Insert into the audit table
insert into AuditTest (
[Type]
,[TableName]
,[PKCol]
,[PK]
,[FieldName]
,[OldValue]
,[NewValue]
,[UpdateDate]
,[DBUsername]
,[UserID]
)
values('u'
, 'Table_QuoteDetail'
, 'QuoteDetail'
, @QuoteDetailID
, 'QTY'
, @dQty
, @iQty
, GETDATE()
, '123'
, '456'
);
PRINT 'AFTER UPDATE Trigger fired.'
END
--- Updating QTY if old/new value change
DECLARE @iUnitSell int; SELECT @iUnitSell = i.UnitSell from inserted i;
DECLARE @dUnitSell int; SELECT @dUnitSell = d.Qty from deleted d;
if update(UnitSell) and exists (select * from deleted d
WHERE UnitSell <> @iUnitSell )
BEGIN
-- Insert into the audit table
insert into AuditTest (
[Type]
,[TableName]
,[PKCol]
,[PK]
,[FieldName]
,[OldValue]
,[NewValue]
,[UpdateDate]
,[DBUsername]
,[UserID]
)
values('u'
, 'Table_QuoteDetail'
, 'QuoteDetail'
, @QuoteDetailID
, 'UnitSell'
, @dUnitSell
, @iUnitSell
, GETDATE()
, '123'
, '456'
);
PRINT 'AFTER UPDATE Trigger fired.'
END
GO