SQL Server: Trigger to track or Log DML queries executed on a specific table

There is a master table in my production server. This table is getting updated from various users from various sources. As this table is very huge and the changes/updates/inserts are in bulk, I cannot maintain old data and updated data track. So I needed a trigger to track DML queries executed on the table by particular user in particular date.

(1) First create a table with the schema. You can customise this table as per your needs.
CREATE TABLE [test]
(
    [ID] [int] IDENTITY(1,1) PRIMARY KEY NOT NULL,
    [DeviceName] [varchar](100) NULL,
    [UserName] [varchar](100) NULL,
    [objectName] [varchar](100) NULL,
    [EventType] [varchar](400) NULL,
    [EventTime] [datetime] NULL,
    [CommandText] [varchar](max) NULL,
)

(2) Create the below Trigger on the table which you want to track query logs.
CREATE TRIGGER [dbo].[TriItemsDMLlog]
ON [dbo].[MasterTable]
AFTER UPDATE,DELETE,INSERT
AS
BEGIN
SET NOCOUNT ON

DECLARE @TABLENAME VARCHAR(20)
SET @TABLENAME='MasterTable'

DECLARE @inputbuffer TABLE
(EventType nvarchar(30),
Parameters int,
EventInfo nvarchar(4000))

INSERT INTO @inputbuffer EXEC('DBCC inputbuffer('+@@Spid+') with no_infomsgs')

DECLARE @INS INT
DECLARE @DEL INT

SELECT @INS=COUNT(*) FROM INSERTED
SELECT @DEL=COUNT(*) FROM DELETED

INSERT INTO MasterTableDMLQueryLog
(
UserName,
DeviceName,
objectname,
EventType,
EventTime,
CommandText
) SELECT SUSER_NAME(),HOST_NAME(),@TABLENAME,
CASE WHEN ISNULL(@INS,0)>0 AND ISNULL(@DEL,0)>0 THEN 'UPDATE'
when ISNULL(@INS,0)>0 AND ISNULL(@DEL,0)=0 THEN 'INSERT'
ELSE 'DELETE'END,GETDATE(),EventInfo FROM @inputbuffer;

SET NOCOUNT OFF

END

No comments:

Post a Comment