An option is DML Trigger, see
How to audit the data change in SQL
We are currently running SQL 2017. We are trying to track the data change with information like DateCreated,CreatedBy for new record added and DataChanged and ChangedBy for data updated or deleted. What is the best way to track these information? Thanks
SQL Server | Other
3 answers
Sort by: Most helpful
-
MikeyQiaoMSFT-0444 3,310 Reputation points2024-04-26T06:03:15.6566667+00:00 Hi,szh8866-8371
SQL Server Audit (Database Engine)(recommend)
Audit can monitor two levels in SQL Server: the server level and the database level. Each level has corresponding Action Groups and Actions. Carefully read the official documentation. Below is a screenshot of my example:
Create a trigger and a log table to record the operations.
Here is an example:
CREATE TRIGGER trgAfterUpdate ON [dbo].[YourTable] AFTER UPDATE AS BEGIN AuditTable INSERT INTO [dbo].[AuditTable] (ModifiedBy, ModifiedDate, Action, Details) SELECT SYSTEM_USER, GETDATE(), 'UPDATE', 'An update has been performed on ID ' + CAST(i.ID AS VARCHAR) FROM inserted i; END;- Temporal tables(As Erland recommended)
- If you just want to audit the DML changes (insert, update, and delete operations) that were made to user tables in a database.
Try this method:
Change data capture and Change tracking.
Best regards,
Mikey Qiao
If the answer is the right solution, please click "Accept Answer" and kindly upvote it.
-
Erland Sommarskog 133.6K Reputation points MVP Volunteer Moderator2024-04-25T21:15:53.4166667+00:00 That depends a whole lot on your requirements. If you want dates for every change, the above is obviously insufficient.
If you want audit of every change, you could consider using temporal tables, but you can also expect your disk usage to grow a lot in that case.