I tried create a trigger:
CREATE TRIGGER DataTrigger ON Data AFTER INSERT , DELETE
AS
BEGIN
IF EXISTS(SELECT * FROM Inserted)
INSERT INTO [dbo].[AuditTrail]
([ActionType]
,[TableName]
,[Name]
,[Time])
('INSERT' //Incorrect syntax near 'INSERT'
,'Data'
,SELECT col1 FROM Inserted
,CURRENT_TIMESTAMP //Incorrect syntax near the keyword 'CURRENT_TIMESTAMP')
END
but it keep saying that I have thoes errors, can somebody show me where I did wrong?
P/S: what is the best way to detect an update?
Thank you
Just for clarification.
Your query, if syntatically correct would have failed if more than one row was inserted, the version above allows for multiple inserts.
The
IF EXISTSwas redundant, which is why it was removed, if there are no rows there will be no insert into your audit table.If you want to audit
DELETEyou’ll need a similar statement again, but using theDeletedtable rather thanInsertedTo audit
UPDATE, create a new trigger, for each updated row you get an entry inInsertedwith the new updates and an entry inDeletedwith the old data, you can join these if you want to track old and new.