数据库 通过表触发器 实时通知应用程序

/*
Sqlserver数据库开始相关服务
以下示例显示了如何查看 OLE Automation Procedures 的当前设置。0未启用
*/
EXEC sp_configure 'show advanced option', '1' --只有这个高级选项被打开的时候,才有权限修改其他配置。
go 
RECONFIGURE     --运行RECONFIGURE语句进行安装,也就是说,使以上语句生效
go 
EXEC sp_configure 'Ole Automation Procedures';
GO

--启用Ole Automation Procedures
sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ole Automation Procedures', 1;
GO
RECONFIGURE;
GO


---通过sql server 2008 调用应用程序  
CREATE PROCEDURE  [dbo].[pro_NotifyApp](
	@Id NVARCHAR(20),
	@Content NVARCHAR(MAX)
)     
AS  
BEGIN  
	declare @ServiceUrl as varchar(1000)   
  
	 PRINT  'http://localhost:789/home/GetNotify?id=' + @Id + '&message=' + @Content 
	--通过http协议调用的接口地址'   
	set @ServiceUrl = 'http://localhost:789/home/GetNotify?id=' + @Id + '&message=' + @Content  
  
	Declare @Object as Int  
	Declare @ResponseText as Varchar(8000)  
  
	Exec sp_OACreate 'MSXML2.XMLHTTP', @Object OUT;  
	Exec sp_OAMethod @Object, 'open', NULL, 'get',@ServiceUrl,'false'  
	Exec sp_OAMethod @Object, 'send'  
	Exec sp_OAMethod @Object, 'responseText', @ResponseText OUTPUT  
  
	Select @ResponseText       
	Exec sp_OADestroy @Object  
END 

--在对应表上创建 更新触发器,监控数据是否有变化,变化即刻通知应用程序
CREATE TRIGGER notify_trigger ON  [dbo].[TestTable]
   AFTER UPDATE 
AS   
BEGIN  
	/*
		update触发器会在更新数据后,
		将更新前的数据保存在deleted表中,更
		新后的数据保存在inserted表中。
	*/
	DECLARE @UpdateID NVARCHAR(20)
	DECLARE @UpdateContent Varchar(MAX) 
    set @UpdateID=(select Deleted.D_Id from Deleted) 
    set @UpdateContent=(select Inserted.D_Amount from Inserted) 

    EXEC pro_NotifyApp @UpdateID, @UpdateContent
END  
        //mvc项目  http://localhost:789/home/GetNotify
        public ActionResult GetNotify()
        {
            string id = Request["id"];
            string message = Request["message"];
            //插入数据
            string txt = string.Empty;
            var date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            txt = string.Format("{0} ID:{1} Message:{2}", date, id, message);
            FileStream fs = null;
            StreamWriter sw = null;
            try
            {
                string path = "D:\111.txt";//文件的路径,保证文件存在。
                fs = new FileStream(path, FileMode.Append);
                sw = new StreamWriter(fs);
                sw.WriteLine(txt);
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                sw.Dispose();
                sw.Close();
                fs.Dispose();
                fs.Close();
            }
            return null;
        }
--测试
/*触发器两个虚拟表,inserted 保存的是 insert 或 update 之后所影响的记录形成的表,
deleted 保存的是 delete 或 update 之前所影响的记录形成的表。*/
UPDATE dbo.TestTable SET  D_Amount=209 WHERE D_Id=5004

原文地址:https://www.cnblogs.com/zxh1919/p/10213001.html