Identify the action that is deleting all rows in a table

为君一笑 提交于 2019-12-01 14:31:43

You can use Extended Events to monitor your system. Here a simple screen shot where are.

A simple policy can monitor for delete and truncate statements. When this events are raised details are written into file.

Here a screen with details (you can configure the script to collect more data) collected for delete statement.

Here the script used, modify the output file path

CREATE EVENT SESSION [CheckDelete] ON SERVER 
ADD EVENT sqlserver.sql_statement_completed(SET collect_statement=(1)
    ACTION(sqlserver.client_connection_id,sqlserver.client_hostname)
    WHERE ([sqlserver].[like_i_sql_unicode_string]([statement],N'%delete%') OR [sqlserver].[like_i_sql_unicode_string]([statement],N'%truncate%'))) 
ADD TARGET package0.event_file(SET filename=N'C:\temp\CheckDelete.xel',max_file_size=(50))
WITH (MAX_MEMORY=4096 KB,EVENT_RETENTION_MODE=ALLOW_SINGLE_EVENT_LOSS,MAX_DISPATCH_LATENCY=30 SECONDS,MAX_EVENT_SIZE=0 KB,MEMORY_PARTITION_MODE=NONE,TRACK_CAUSALITY=OFF,STARTUP_STATE=OFF)
GO

This is a possibility that may help you. It creates a trigger on Table1 that sends an email when a process DELETEs more than 100 records. I'd modify the message to include some useful data like:

  1. Process ID (@@SPID)
  2. Host (HOST_NAME())
  3. Name of app (APP_NAME())
  4. And possibly the entire query

CREATE TRIGGER Table1MassDeleteTrigger
ON dbo.Activities
FOR DELETE 
AS
    DECLARE @DeleteCount INT = (SELECT COUNT(*) FROM deleted)

    IF(@DeleteCount > 100)
        EXEC msdb.dbo.sp_send_dbmail
        @profile_name = 'MailProfileName',
        @recipients = 'admin@yourcompany.com',
        @body = 'Something is deleting all your data!',
        @subject = 'Oops!';
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!