Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to start SQL Server job from a stored procedure?

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

like image 501
g_shockTan Avatar asked Apr 09 '13 16:04

g_shockTan


People also ask

How do I start a job in SQL?

In Object Explorer, connect to an instance of the SQL Server Database Engine, and then expand that instance. Expand SQL Server Agent. Right-click Job Activity Monitor and click View Job Activity. In the Job Activity Monitor, you can view details about each job that is defined for this server.

How do you call a stored procedure in a scheduled job in SQL Server?

Expand SQL Server Agent, expand Jobs, right-click the job that you want to schedule, and click Properties. Select the Schedules page, and then click Pick. Select the schedule that you want to attach, and then click OK.

How do I execute a stored procedure in SQL Agent?

Expand the SQL Server Agent and right click on Jobs and click on New Job… In General tab, Enter job name, owner, category and description. In Steps tab, click New and enter step name, select Type as Transact-SQL script (T-SQL) and select database and put EXEC procedure name in command area.


1 Answers

-- 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
like image 184
Mark Schultheiss Avatar answered Oct 19 '22 14:10

Mark Schultheiss