How to start SQL Server job from a stored procedure?

陌路散爱 提交于 2019-12-19 12:49:09

问题


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


回答1:


You can execute the stored procedure sp_start_job in your stored procedure.

See here: http://msdn.microsoft.com/en-us/library/ms186757.aspx




回答2:


-- 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



回答3:


Create your store procedure and run the job inside your proc as follows:

DECLARE @JobId binary(16)
SELECT @JobId = job_id FROM msdb.dbo.sysjobs WHERE (name = 'JobName')

IF (@JobId IS NOT NULL)
BEGIN
    EXEC msdb.dbo.sp_start_job @job_id = @JobId;
END


来源:https://stackoverflow.com/questions/15906923/how-to-start-sql-server-job-from-a-stored-procedure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!