SQL Server 代理作业 - 存在然后删除?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/136771/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
SQL Server Agent Job - Exists then Drop?
提问by madcolor
How can I drop an sql server agent jobs, if (and only if) it exists?
如果(且仅当)存在 sql server 代理作业,我该如何删除它?
This is a well functioning script for stored procedures. How can I do the same to sql server agent jobs?
这是一个运行良好的存储过程脚本。如何对 sql server 代理作业执行相同的操作?
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] ...
回答by Codewerks
Try something like this:
尝试这样的事情:
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'
Best to read the docs on all the parameters required for 'sp_add_job'and 'sp_delete_job'
最好阅读有关“sp_add_job”和“sp_delete_job”所需的所有参数的文档
回答by Seshu
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
回答by Andy Jones
If you generate the SQL script for a job (tested with enterprise manager), it automatically builds the check for existance and drop statements for you. Example below: -
如果您为作业生成 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