I need to create a trigger on SQL Server to write only updated column into an audit table with table name, column name, previous/new value, date, time and user for specific
We’re using third party tool ApexSQL Audit to generate audit triggers since we have a lot of tables that require auditing.
If you don’t need a third party tool you can use this in trial mode and see how they are implementing triggers and storage tables.
Below is a sample trigger and storage tables I picked up quickly from my database.
Data storage table:
Table that stores details about transactions:
Here is a sample of delete trigger. Note the comment inline
CREATE TRIGGER [dbo].[tr_d_AUDIT_Table_Name]
ON [dbo].[Table_Name]
FOR DELETE
NOT FOR REPLICATION
AS
BEGIN
DECLARE
@IDENTITY_SAVE varchar(50),
@AUDIT_LOG_TRANSACTION_ID Int,
@PRIM_KEY nvarchar(4000),
@ROWS_COUNT int
SET NOCOUNT ON
Select @ROWS_COUNT=count(*) from deleted
Set @IDENTITY_SAVE = CAST(IsNull(@@IDENTITY,1) AS varchar(50))
INSERT
INTO dbo.AUDIT_LOG_TRANSACTIONS
(
TABLE_NAME,
TABLE_SCHEMA,
AUDIT_ACTION_ID,
HOST_NAME,
APP_NAME,
MODIFIED_BY,
MODIFIED_DATE,
AFFECTED_ROWS,
[DATABASE]
)
values(
'Table_Name',
'dbo',
3,
CASE
WHEN LEN(HOST_NAME()) < 1 THEN ' '
ELSE HOST_NAME()
END,
CASE
WHEN LEN(APP_NAME()) < 1 THEN ' '
ELSE APP_NAME()
END,
SUSER_SNAME(),
GETDATE(),
@ROWS_COUNT,
'database_name'
)
Set @AUDIT_LOG_TRANSACTION_ID = SCOPE_IDENTITY()
INSERT
INTO dbo.AUDIT_LOG_DATA
(
AUDIT_LOG_TRANSACTION_ID,
PRIMARY_KEY_DATA,
COL_NAME,
OLD_VALUE_LONG,
DATA_TYPE
, KEY1
)
SELECT
@AUDIT_LOG_TRANSACTION_ID,
convert(nvarchar(1500), IsNull('[Order_ID]='+CONVERT(nvarchar(4000), OLD.[Order_ID], 0), '[Order_ID] Is Null')),
'Order_ID',
CONVERT(nvarchar(4000), OLD.[Order_ID], 0),
'A'
, CONVERT(nvarchar(500), CONVERT(nvarchar(4000), OLD.[Order_ID], 0))
FROM deleted OLD
WHERE
OLD.[Order_ID] Is Not Null
/*
Insert statement above is replicated for each column being audited
*/
END