我想删除所有当前未运行且描述为“xxxx”的 SQL 代理作业。这如何在脚本中完成?
到目前为止,我已经完成了如下操作,并且肯定会有更好的方法。
DECLARE @job_owner_name VARCHAR(100)
DECLARE @MaxJobs INT
declare @RowCnt INT
DECLARE @jobId NVARCHAR(36)
select @RowCnt = 1
SET @job_owner_name = ''
IF OBJECT_ID('tempdb..#xp_results') IS NOT NULL
DROP TABLE #xp_results
Declare @xp_results TABLE
( job_id UNIQUEIDENTIFIER NOT NULL,
last_run_date INT NOT NULL,
last_run_time INT NOT NULL,
next_run_date INT NOT NULL,
next_run_time INT NOT NULL,
next_run_schedule_id INT NOT NULL,
requested_to_run INT NOT NULL,
request_source INT NOT NULL,
request_source_id SYSNAME COLLATE database_default NULL,
running INT NOT NULL,
current_step INT NOT NULL,
current_retry_attempt INT NOT NULL,
job_state INT NOT NULL
)
INSERT INTO @xp_results
EXEC master.dbo.xp_sqlagent_enum_jobs 1, ''
Declare @jobs TABLE (rownum int IDENTITY (1, 1) Primary key NOT NULL ,
job_id UNIQUEIDENTIFIER NOT NULL)
INSERT INTO @jobs
SELECT rj.job_id
FROM @xp_results rj
INNER JOIN msdb.dbo.sysjobs sj ON sj.job_id = rj.job_id
WHERE rj.running <>1
AND sj.[description] = 'MasterJobHanlder'
SELECT @MaxJobs = COUNT(*) FROM @jobs
WHILE @RowCnt <= @MaxJobs
BEGIN
SELECT @jobId = job_id FROM @jobs WHERE rownum = @rowcnt
SELECT @jobID
EXEC msdb.dbo.sp_delete_job @job_id = @jobid, @delete_unused_schedule=1
Select @RowCnt = @RowCnt + 1
END
请有任何进一步的想法