如何在作业 created/deleted 时触发 SQL Server 2008

How to have SQL Server 2008 trigger when a job is created/deleted

如何设置 SQL Server 2008 触发器以在作业 Created/Deleted

时发送电子邮件警报

我在许多小时的研究的帮助下创建了一个触发器。当 SQL 工作 enabled/disabled 时,触发器当前会通过电子邮件发送给收件人。触发器已经过测试并且可以正常工作。

我想扩展触发器以捕获作业的创建和删除,但我不确定如何。

这是我的代码:

USE [msdb]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER TRIGGER [dbo].[jobChecker] 
ON sysjobs 
FOR UPDATE AS 
SET NOCOUNT ON

-- # DECLARE VARIABLES # --

DECLARE @username VARCHAR(50), 
  @hostName VARCHAR(50), 
  @jobName VARCHAR(100),
  @newEnabled INT, 
  @oldEnabled INT,
  @jobCreated INT,
  @bodyText VARCHAR(200), 
  @subjectText VARCHAR(200),
  @servername VARCHAR(50),
  @profileName VARCHAR(50) = 'profile_name',
  @recipients VARCHAR(500) = 'example@domain.com'

-- # SET VARIABLES # --

SELECT @username = SYSTEM_USER
SELECT @hostName = HOST_NAME()
SELECT @servername = @@servername
SELECT @newEnabled = ENABLED FROM Inserted
SELECT @oldEnabled = ENABLED FROM Deleted
SELECT @jobName = Name FROM Inserted 

-- # CHECK FOR ENABLED/DISABLED # --

IF @newEnabled <> @oldEnabled 
BEGIN 

  IF @newEnabled = 1 
  BEGIN 
    SET @bodyText = 'The user (' + @username + ') enabled the job from ' + @hostName + ' on ' + CONVERT(VARCHAR(20),GETDATE(),100) + '.'
    SET @subjectText = @servername + ' : [' + @jobName + '] has been ENABLED'
  END 

  IF @newEnabled = 0 
  BEGIN 
    SET @bodyText = 'The user (' + @username + ') disabled the job from ' + @hostName + ' on ' + CONVERT(VARCHAR(20),GETDATE(),100) + '.'
    SET @subjectText = @servername+' : [' + @jobName + '] has been DISABLED' 
  END 

  SET @subjectText = 'SQL Job on ' + @subjectText 

-- # SEND EMAIL # --

  EXEC msdb.dbo.sp_send_dbmail 
  @profile_name = @profileName,
  @recipients = @recipients,
  @body = @bodyText, 
  @subject = @subjectText 

END

尝试将 "FOR UPDATE" 更改为 "AFTER UPDATE, INSERT, DELETE" 这应该 运行 触发然后从 table

中插入和删除

然后您可以通过 运行ning 类似

的方式检查它是否是更新、插入或删除

声明@Type 为 varchar(1); 设置@Type = ( 案件 WHEN EXISTS(SELECT * FROM INSERTED) AND EXISTS(SELECT * FROM DELETED) THEN 'U' -- 然后记录被更新。 WHEN EXISTS(SELECT * FROM INSERTED) THEN 'I' --记录被插入。 WHEN EXISTS(SELECT * FROM DELETED) THEN 'D' --记录被删除。 否则为空
结束)