我有以下查询生成必要的命令,以禁用特定于某个类别的所有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'
如何完全自动完成此操作,以便生成命令并执行它们而不是手动过程?
答案 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;