0

我有下面的 EmployeeData 表,由于一些已知的原因,BAD 数据被插入,我正在修复代码,但同时我想检查错误数据,直到部署修复程序。如果您观察到 John的ActiveIsEmpTermed列都为1 。

在此处输入图像描述

目前我正在运行以下查询以在 SQL Server 中手动检查错误数据。如果发现错误数据,即Active =1IsEmpTermed =1,我想自动执行此任务并向我发送电子邮件。什么和怎么做?

select * from EmployeeData Where Active=1 and IsEmpTermed = 1;

提前致谢。

4

1 回答 1

1

快速的方法是使用带有sp_send_dbmail的 @query 参数并将该代码放入 SQL Server 代理作业中。

下面是 sp_send_dbmail 的简单示例:

EXEC msdb.dbo.sp_send_dbmail 
    @profile_name = ''  --This is specific to your setup
   ,@recipients = 'your@email.com'
   ,@subject = 'This is the subject'
   ,@query = 'select EmpID, FirstName, LastName from EmployeeData Where Active=1 and IsEmpTermed = 1' --The query
   ,@execute_query_database = ''  --The name of your database goes here where the query should be executed

这将基本上执行您在@query 中指定的查询,将结果转储到电子邮件中并将其发送给@recipients 中的任何人

如果您不知道您的服务器配置的 @profile_name 是什么,您可以运行

EXEC msdb.dbo.sysmail_help_profileaccount_sp; 

这将返回在您的服务器上配置的邮件配置文件列表。您将使用“profile_name”列中的值。如果有多个,这是我无法告诉您的,因为它特定于您的服务器配置。

通过在 SSMS 中手动运行它来定义和工作后,使用 T-SQL 步骤创建 SQL Server 代理作业并添加“EXEC msdb.dbo.sp_send_dbmail”代码。 以您希望它运行的任何频率定义一个时间表。

很多时候我会在发送电子邮件之前对其进行编码以检查数据问题是否存在,因此它只会在数据问题存在时发送电子邮件,因此如果没有问题,它就不会继续向我发送垃圾邮件,像这样

--The IF EXISTS checks if the data issue exists before sending an email
IF EXISTS(SELECT TOP 1 'x' FROM dbname.dbo.EmployeeData Where Active=1 and IsEmpTermed = 1)
BEGIN
        EXEC msdb.dbo.sp_send_dbmail 
            @profile_name = ''  --This is specifc to your setup
           ,@recipients = 'your@email.com'
           ,@subject = 'This is the subject'
           ,@query = 'select EmpID, FirstName, LastName from EmployeeData Where Active=1 and IsEmpTermed = 1' --The query
           ,@execute_query_database = ''  --The name of your database goes here
END
于 2020-07-17T13:51:31.807 回答