How to start SQL Server job from a stored procedure?

g_shockTan picture g_shockTan · Apr 9, 2013 · Viewed 64.9k times · Source

How can I create a stored procedure to start a SQL Server job?

Answer

Mark Schultheiss picture Mark Schultheiss · Apr 9, 2013
-- Create SQL Server Agent job start stored procedure with input parameter
CREATE PROC uspStartMyJob @MyJobName sysname
AS
DECLARE @ReturnCode tinyint -- 0 (success) or 1 (failure)
EXEC @ReturnCode=msdb.dbo.sp_start_job @job_name=@MyJobName;
RETURN (@ReturnCode)
GO

OR with no parameter:

-- Create stored procedure to start SQL Server Agent job
CREATE PROC StartMyMonthlyInventoryJob
AS
EXEC msdb.dbo.sp_start_job N'Monthly Inventory Processing';
GO
-- Execute t-sql stored procedure
EXEC StartMyMonthlyInventoryJob

EDIT FYI: You can use this PRIOR to starting IF you don't want to start the job IF it is running currently, work this in your stored proc:

-- Get run status of a job
-- version for SQL Server 2008 T-SQL - Running = 1 = currently executing
 -- use YOUR guid here
DECLARE @job_id uniqueidentifier = '5d00732-69E0-2937-8238-40F54CF36BB1' 
EXEC master.dbo.xp_sqlagent_enum_jobs 1, sa, @job_id