SQL Server代理作业 - 存在然后删除?

时间:2008-09-25 23:07:31

标签: sql sql-server sql-server-agent sql-job

如果(并且仅当)它存在,我如何删除sql server代理作业?

这是存储过程的功能良好的脚本。如何对sql server agent作业执行相同的操作?

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[storedproc]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
    drop procedure [dbo].[storedproc]
GO
CREATE PROCEDURE [dbo].[storedproc] ...

3 个答案:

答案 0 :(得分:83)

尝试这样的事情:

DECLARE @jobId binary(16)

SELECT @jobId = job_id FROM msdb.dbo.sysjobs WHERE (name = N'Name of Your Job')
IF (@jobId IS NOT NULL)
BEGIN
    EXEC msdb.dbo.sp_delete_job @jobId
END

DECLARE @ReturnCode int
EXEC @ReturnCode =  msdb.dbo.sp_add_job @job_name=N'Name of Your Job'

最好阅读有关'sp_add_job''sp_delete_job'

所需的所有参数的文档

答案 1 :(得分:20)

IF EXISTS (SELECT job_id 
            FROM msdb.dbo.sysjobs_view 
            WHERE name = N'Your Job Name')
EXEC msdb.dbo.sp_delete_job @job_name=N'Your Job Name'
                            , @delete_unused_schedule=1

答案 2 :(得分:2)

如果为作业生成SQL脚本(使用企业管理器测试),它会自动为您构建存在和删除语句的检查。示例如下: -

DECLARE @JobID BINARY(16)   
DECLARE @ReturnCode INT  
SELECT @ReturnCode = 0  
-- Delete the job with the same name (if it exists)  
SELECT @JobID = job_id   
FROM  msdb.dbo.sysjobs  
WHERE (name = N'My test job')   
IF (@JobID IS NOT NULL)  
BEGIN  
-- Check if the job is a multi-server job  
IF (EXISTS (SELECT *   
FROM msdb.dbo.sysjobservers   
WHERE (job_id = @JobID) AND (server_id <> 0)))   
BEGIN   
-- There is, so abort the script   
RAISERROR (N'Unable to import job ''My test job'' since there is already a multi-server   job with this name.', 16, 1) 
END   
ELSE   
-- Delete the [local] job   
EXECUTE msdb.dbo.sp_delete_job @job_name = N'My test job'   
SELECT @JobID = NULL  
END