LongRunning Automation
LongRunning Automation
com
SQL Agent Job: Kill Long-Running Processes with Exclusion , Logging killed processes and
Send Notification to the respective login and the DBA Team.
Objective:
The goal is to create a SQL Agent job that identifies and terminates processes running longer than a
specified time, excludes specific job processes from termination, sends an email notification to the
respective user, and logs the killed processes in a custom table.
Components Overview:
1. Exclusion Table: Stores job names and their maximum allowed runtime.
2. Killed Processes Log Table: Stores details of killed processes for auditing purposes.
3. SQL Script: Identifies long-running processes, excludes specified jobs, kills the remaining
processes, sends email notifications, and logs the details in the log table.
Create a table to store job names and their maximum allowed runtime.
);
Insert job names and their respective maximum allowed runtime in minutes.
VALUES
);
This script identifies long-running processes, excludes jobs in the exclusion list, kills the remaining
processes, sends an email to the login, and logs the details in the log table.
FROM sys.dm_exec_requests r
Meet me on SQLTasks.com
SELECT MAX(MaxRunTimeMinutes)
FROM dbo.JobExclusionList
-- Open cursor
OPEN LongRunningProcesses;
WHILE @@FETCH_STATUS = 0
BEGIN
SET @EmailBody = 'The process with SPID ' + CAST(@SPID AS NVARCHAR(10)) + ' executed by ' +
@LoginName
EXEC msdb.dbo.sp_send_dbmail
@profile_name = @ProfileName,
@subject = @Subject,
@body = @EmailBody;
PRINT 'Killed SPID: ' + CAST(@SPID AS NVARCHAR(10)) + ', Email sent to: ' + @LoginName;
END;
-- Close cursor
CLOSE LongRunningProcesses;
DEALLOCATE LongRunningProcesses;
Ensure Database Mail is enabled and configured to send emails from SQL Server.
RECONFIGURE;
RECONFIGURE;
EXEC msdb.dbo.sysmail_add_profile_sp
@profile_name = 'DBA_Mail_Profile',
EXEC msdb.dbo.sysmail_add_account_sp
@account_name = 'DBA_Email_Account',
@email_address = '[email protected]',
@mailserver_name = 'smtp.example.com';
EXEC msdb.dbo.sysmail_add_profileaccount_sp
@profile_name = 'DBA_Mail_Profile',
@account_name = 'DBA_Email_Account',
@sequence_number = 1;
EXEC msdb.dbo.sp_set_sqlagent_properties
@mail_profile = 'DBA_Mail_Profile';
Summary
• Send email notifications to the login associated with the killed process.