SQL server 表数据改变触发发送邮件的方法


今天遇到一个问题,原有生产系统正在健康运行,现需要监控一张数据表,当增加数据的时候,给管理员发送邮件。

领到这个需求后,有同事提供方案:写触发器触发外部应用程序。这是个大胆的想法啊,从来没写过这样的触发器。

以下是参考文章:

第一种方法: 触发器调用外部程序。 xp_cmdshell

http://www.phpstudy.net/article/90714.htm 第一篇提供的方法是需要开启xp_cmdshell

先开启xp_cmdshell

打开外围应用配置器—>

功能的外围应用配置器—>

实例名\Database Engine\xp_cmdshell—>

启用

然后可以调用外部程序:Exec xp_cmdshell 'c:\calc.exe' 。

第二种方法:将插入的值传给.bat 。同样使用调用外部程序的 xp_cmdshell 的权限

http://www.sqlparty.com/%E9%A2%98%E7%82%BC/2013/08/05/e5-a6-82-e4-bd-95-e5-9c-a8-e6-9f-90-e8-a1-a8-e6-96-b0-e6-8f-92-e5-85-a5-e6-95-b0-e6-8d-ae-e6-97-b6-e8-a7-a6-e5-8f-91-e6-89-a7-e8-a1-8c-e5-a4-96-e9-83-a8-e7-a8-8b-e5-ba-8f-ef-bc-9f.html

其实第二种方法可以归为第一种。

下面说说第三种方法:

SQL servere CLR

这种方法可以利用VS给sql server 写存储过程和触发器。打开了VS不愁写代码给管理员发email。

第四种方法:

SQL server Management -->Database Mail

开启Database Mail 之后,配制好发邮件的设置,直接写触发器就可以把插入的内容通过sql server 发送出来了。

Create TRIGGER tri_email 
ON [dbo].[ImageGalleries]
AFTER insert
AS
BEGIN
if exists(select * from inserted)
begin
declare @content nvarchar(max)
select @content=i.Name+'|'+i.ImagePath from inserted i;
exec msdb.dbo.sp_send_dbmail @profile_name='SQLProfile',
@recipients=243594541@qq.com',
@subject='sql server send email by trigger',
@body=@content
end
END
GO 

这种方法是最直接最简便的方法。


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3