Counter of Festivals

Ashok Blog for SQL Learners and Beginners and Experts

Tuesday, 30 October 2018

TSQL query to found job is running more than 24 hours then stop it

----TSQL query to found job is running more than 24 hours then stop it--

DECLARE @elapsed_minutes_max int
SET @elapsed_minutes_max = 1440 --24 hours, adjust as needed

IF OBJECT_ID('tempdb.dbo.#jobactivity') IS NOT NULL
DROP TABLE #jobactivity
CREATE TABLE #jobactivity (
session_id int NULL,
job_id uniqueidentifier NULL,
job_name sysname NULL,
run_requested_date datetime NULL,
run_requested_source sysname NULL, --1=via schedule; 2=via alert; 3=via startup; 4=via user; 6=via CPU idle.
queued_date datetime NULL,
start_execution_date datetime NULL,
last_executed_step_id int NULL,
last_executed_step_date datetime NULL,
stop_execution_date datetime NULL,
next_scheduled_run_date datetime NULL,
job_history_id int NULL,
message nvarchar(1024) NULL,
run_status int NULL,
operator_id_emailed int NULL,
operator_id_netsent int NULL,
operator_id_paged int NULL
)

INSERT INTO #jobactivity
EXEC msdb.dbo.sp_help_jobactivity

--if the backup job is running ...
IF EXISTS(
SELECT *
FROM #jobactivity ja
WHERE
    ja.start_execution_date IS NOT NULL AND
    ja.stop_execution_date IS NOT NULL AND
    DATEDIFF(MINUTE, ja.start_execution_date, GETDATE()) >= @elapsed_minutes_max
AND ja.job_name = N'job_name')
BEGIN
    --... stop it
    --EXEC msdb.dbo.sp_stop_job N'job_name>'
print 'stop it'
END --IF

ELSE
BEGIN
--SELECT @elapsed_minutes_max

PRINT 'No JOB FOUND'

END

drop table #jobactivity