我有一个T-SQL存储过程(它返回一个称为@HourDifference
的标量值作为输出参数);您可以在下面看到执行情况:
DECLARE @HourDifference_output TINYINT;
-- I declare a variable to capture the output parameter--
EXEC dbo.sproc_XYZ_Notification
@HourDifference = @HourDifference_output OUTPUT;
SELECT @HourDifference_output AS HourDifferenceCaptured
我有以下要求:
如果HourDifferenceCaptured > 12
,我需要发送电子邮件
如果为HourDifferenceCaptured <= 12
,则无需发送电子邮件;不需要做任何事情。
我需要有两个计划,一个在SQL Server代理中,在上午7点,另一个在7 PM。
有人可以提供代码并指导我完成此过程吗?
USE <database_name>
GO
DECLARE @subject NVARCHAR(max) = 'Email subject'
, @body NVARCHAR(MAX)
DECLARE @HourDifference_output TINYINT;
EXEC dbo.sproc_XYZ_Notification @HourDifference = @HourDifference_output OUTPUT;
SELECT @HourDifference_output AS HourDifferenceCaptured
IF (@HourDifference_output> 12)
BEGIN
SET @body = '<!DOCTYPE html>
<html>
<body>
<body style="color:black; font-family:Times New Roman; font-size:14x"> .......... body text ......... </body>
<body style="color:SlateGray; font-family:Times New Roman; font-size:14px;line-height: 1;"> ------------------------------------------------------------------' + '
<body style="color:SlateGray; font-family:Times New Roman; font-size:14px;line-height: 1;"> ------------------------------------------------------------------' + '
</body>
</HTML>'
EXEC msdb.dbo.sp_send_dbmail @profile_name = 'Profile name'
, @recipients = 'distibution email'
, @body = @body
, @body_format = 'HTML'
, @subject = @subject
END
GO
您可以创建一个t-sql步骤的SQL Server代理作业,该步骤在需要时使用msdb.dbo.sp_send_dbmail
发送电子邮件(有关存储过程的完整参考,请参见here)。
尝试类似以下内容:
DECLARE @HourDifference_output TINYINT;
EXEC dbo.sproc_XYZ_Notification @HourDifference_output OUTPUT;
-- SELECT @HourDifference_output AS HourDifferenceCaptured
IF @HourDifference_output > 12
BEGIN
EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'db_mail_profile_i_have_already_created',
@recipients = '[email protected]',
@body = 'Too many hours difference.',
@subject = 'Automated Message' ;
END
您必须已经配置了database mail account,database mail profile,并已授予运行作业步骤的用户适当的访问权限。第二个链接还包含用于创建数据库邮件帐户和配置文件,将帐户添加到配置文件并适当地授予访问权限的示例脚本(我个人更喜欢通过SSMS db邮件向导配置数据库邮件)。
要做的决定是创建公开个人资料还是私人个人资料。您可以找到有关差异here的更多信息。
最后,我认为,当作业/步骤失败时,最好通过SQL Server Agent内置机制通知管理员。