如何发送有关在 sql 服务器中的 table 中发现错误数据的电子邮件

How to send an email on finding bad data in a table in sql server

我有以下 EmployeeData table,并且由于某些已知原因,正在插入错误数据,我正在修复代码,但同时我想检查错误数据,直到部署修复程序。如果您观察到 John 1 用于 ActiveIsEmpTermed 列。

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

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

提前致谢。

快速方法是将@query 参数与sp_send_dbmail 一起使用,并将该代码放入SQL 服务器代理作业中。

这是 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; 

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

在 SSMS 中通过手动 运行 完成所有定义和工作后,以您希望的任何频率转到 create a SQL Server Agent Job with a T-SQL step and add the "EXEC msdb.dbo.sp_send_dbmail" code. Defined a schedule 运行。

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

--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