1

我想删除所有当前未运行且描述为“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

请有任何进一步的想法

4

1 回答 1

1

我没有测试这么多,但这样的事情似乎会起作用:

USE msdb

DECLARE @deleteCmd nvarchar(max);
SET @deleteCmd = '';

SELECT @deleteCmd =  @deleteCmd 
  + ( 'exec dbo.sp_delete_job @job_name = ''' 
  + replace( j.name, '''', '''''' ) + '''; ' 
  + char(10) )
FROM dbo.sysjobs j
WHERE j.[description] like '%foo%'
AND not exists (
    SELECT 1
    FROM dbo.sysjobactivity a
    WHERE a.job_id = j.job_id
      AND a.start_execution_date IS NOT NULL
      AND a.stop_execution_date IS NULL
)

PRINT @deleteCmd --print for troubleshooting

-- really: EXECUTE( @deleteCmd )

信用:http ://timlaqua.com/2009/05/a-cleaner-way-to-detect-the-state-of-a-sql-server-agent-job-in-sql-server-2005/

于 2009-12-22T23:11:42.300 回答