禁用特定类别中的所有SQL代理作业

时间:2017-08-29 05:21:04

标签: sql sql-server tsql sql-server-2016 sql-server-agent

我有以下查询生成必要的命令,以禁用特定于某个类别的所有SQL代理作业。

Select 'Exec MSDB.dbo.sp_update_job @job_name = N''' + SJ.Name + ''', @Enabled = 0'
  FROM msdb..sysjobs SJ inner join msdb..syscategories SC
    on SJ.category_id = SC.category_id
 Where SJ.[Enabled] = 1
   and SC.Name = 'BI ETLs'

如何完全自动完成此操作,以便生成命令并执行它们而不是手动过程?

1 个答案:

答案 0 :(得分:1)

您可以使用动态SQL:

DECLARE @sql NVARCHAR(MAX);

SET @sql = STUFF((    
  SELECT ';' + 'Exec MSDB.dbo.sp_update_job @job_name = N''' 
           + SJ.Name + ''', @Enabled = 0'
  FROM msdb..sysjobs SJ JOIN msdb..syscategories SC
    ON SJ.category_id = SC.category_id
 WHERE SJ.[Enabled] = 1
   and SC.Name = 'BI ETLs' FOR XML PATH('')),1 ,1, '') ;

EXEC dbo.sp_executesql @sql;

使用SQL Server 2017,使用STRING_AGG连接字符串要容易得多:

DECLARE @sql NVARCHAR(MAX);

SET @sql = (Select STRING_AGG('Exec MSDB.dbo.sp_update_job @job_name = N''' + SJ.Name + ''', @Enabled = 0', ';')
  FROM msdb..sysjobs SJ inner join msdb..syscategories SC
    on SJ.category_id = SC.category_id
 Where SJ.[Enabled] = 1
   and SC.Name = 'BI ETLs');

EXEC dbo.sp_executesql @sql;