0% found this document useful (0 votes)
8 views6 pages

LongRunning Automation

The document outlines the creation of a SQL Agent job to manage long-running processes in SQL Server. It includes steps to create exclusion and logging tables, a SQL script to identify and terminate processes exceeding their runtime, and send email notifications. Additionally, it details the configuration of Database Mail and scheduling of the job for regular execution.

Uploaded by

Vignesh M
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views6 pages

LongRunning Automation

The document outlines the creation of a SQL Agent job to manage long-running processes in SQL Server. It includes steps to create exclusion and logging tables, a SQL script to identify and terminate processes exceeding their runtime, and send email notifications. Additionally, it details the configuration of Database Mail and scheduling of the job for regular execution.

Uploaded by

Vignesh M
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Meet me on SQLTasks.

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.

Step 1: Create Exclusion Table

Create a table to store job names and their maximum allowed runtime.

CREATE TABLE dbo.JobExclusionList

JobName NVARCHAR(255) NOT NULL,

MaxRunTimeMinutes INT NOT NULL

);

Populate the Exclusion Table

Insert job names and their respective maximum allowed runtime in minutes.

INSERT INTO dbo.JobExclusionList (JobName, MaxRunTimeMinutes)

VALUES

('Nightly Backup Job', 180), -- 3 hours

('Daily ETL Process', 240), -- 4 hours

('Data Sync Job', 150); -- 2.5 hours

Step 2: Create the Killed Processes Log Table

Create a table to log details of all killed processes.


Meet me on SQLTasks.com

CREATE TABLE dbo.KilledProcessesLog

KillID INT IDENTITY(1,1) PRIMARY KEY,

SPID INT NOT NULL,

LoginName NVARCHAR(255) NOT NULL,

ProgramName NVARCHAR(255) NULL,

HostName NVARCHAR(255) NULL,

StartTime DATETIME NOT NULL,

KillTime DATETIME NOT NULL DEFAULT GETDATE(),

KillReason NVARCHAR(500) NOT NULL

);

Step 3: SQL Script for Killing Processes and Logging Them

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.

DECLARE @SPID INT;

DECLARE @SQL NVARCHAR(1000);

DECLARE @LoginName NVARCHAR(255);

DECLARE @ProgramName NVARCHAR(255);

DECLARE @HostName NVARCHAR(255);

DECLARE @StartTime DATETIME;

DECLARE @EmailBody NVARCHAR(MAX);

DECLARE @Subject NVARCHAR(255);

DECLARE @ProfileName NVARCHAR(100) = 'DBA_Mail_Profile'; -- Your Database Mail profile

-- Cursor to find processes that have exceeded their maximum runtime

DECLARE LongRunningProcesses CURSOR FOR

SELECT r.session_id, s.login_name, s.program_name, s.host_name, r.start_time

FROM sys.dm_exec_requests r
Meet me on SQLTasks.com

INNER JOIN sys.dm_exec_sessions s ON r.session_id = s.session_id

WHERE DATEDIFF(MINUTE, r.start_time, GETDATE()) > ISNULL(

SELECT MAX(MaxRunTimeMinutes)

FROM dbo.JobExclusionList

WHERE r.command LIKE '%' + JobName + '%'

), 180) -- Default to 180 minutes

AND s.host_name NOT LIKE 'SQLAgent%';

-- Open cursor

OPEN LongRunningProcesses;

FETCH NEXT FROM LongRunningProcesses INTO @SPID, @LoginName, @ProgramName,


@HostName, @StartTime;

WHILE @@FETCH_STATUS = 0

BEGIN

-- Build the KILL command

SET @SQL = 'KILL ' + CAST(@SPID AS NVARCHAR(10));

-- Execute the KILL command

EXEC sp_executesql @SQL;

-- Prepare the email notification

SET @Subject = 'SQL Server Process Termination Alert';

SET @EmailBody = 'The process with SPID ' + CAST(@SPID AS NVARCHAR(10)) + ' executed by ' +
@LoginName

+ ' was terminated because it exceeded the allowed runtime limit.';


Meet me on SQLTasks.com

-- Send the email

EXEC msdb.dbo.sp_send_dbmail

@profile_name = @ProfileName,

@recipients = @LoginName + '@example.com', -- Customize the domain as needed

@subject = @Subject,

@body = @EmailBody;

-- Log the killed process in the table

INSERT INTO dbo.KilledProcessesLog (SPID, LoginName, ProgramName, HostName, StartTime,


KillReason)

VALUES (@SPID, @LoginName, @ProgramName, @HostName, @StartTime, 'Process exceeded


allowed runtime limit.');

-- Print log message (Optional)

PRINT 'Killed SPID: ' + CAST(@SPID AS NVARCHAR(10)) + ', Email sent to: ' + @LoginName;

FETCH NEXT FROM LongRunningProcesses INTO @SPID, @LoginName, @ProgramName,


@HostName, @StartTime;

END;

-- Close cursor

CLOSE LongRunningProcesses;

DEALLOCATE LongRunningProcesses;

Step 4: Enable and Configure Database Mail

Ensure Database Mail is enabled and configured to send emails from SQL Server.

Enable Database Mail

EXEC sp_configure 'show advanced options', 1;

RECONFIGURE;

EXEC sp_configure 'Database Mail XPs', 1;


Meet me on SQLTasks.com

RECONFIGURE;

Create a Mail Profile

EXEC msdb.dbo.sysmail_add_profile_sp

@profile_name = 'DBA_Mail_Profile',

@description = 'Profile for sending process termination alerts';

EXEC msdb.dbo.sysmail_add_account_sp

@account_name = 'DBA_Email_Account',

@description = 'Mail account for alerts',

@email_address = '[email protected]',

@display_name = 'SQL Server Alerts',

@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';

Step 5: Create and Schedule the SQL Agent Job

1. Open SQL Server Management Studio (SSMS).

2. Navigate to SQL Server Agent > Jobs.

3. Create a new job with the following steps:

o Step 1: Execute the provided SQL script.

4. Schedule the job to run at regular intervals (e.g., every 30 minutes).


Meet me on SQLTasks.com

Summary

This SQL Agent job script provides a complete solution to:

• Kill processes running longer than the allowed time.

• Exclude specific job processes from termination.

• Send email notifications to the login associated with the killed process.

• Log the killed processes for auditing purposes.

You might also like