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