当新记录插入到DB 时触发Windows服务

可能重复:
使用Sql Server 2008更改通知

我只是想知道无论如何我可以在C#中编写一个Windows服务,当新记录插入数据库时​​将触发该服务。

而且我想通过wcf连接数据库。 请提出任何想法或建议。

提前致谢。

基于demo.b指令,这是代码。

SQL数据库细节


我的数据库名称:MyWeb,表名:StoryItems,列:位置,标题,名称,类型。


public partial class Triggers { // Enter existing table or view for the target and uncomment the attribute line [Microsoft.SqlServer.Server.SqlTrigger(Name = "Trigger_Web", Target = "StoryItems", Event = "FOR INSERT")] public static void Trigger_Web() { SqlCommand command; SqlTriggerContext triggerContext = SqlContext.TriggerContext; SqlPipe pipe = SqlContext.Pipe; SqlDataReader reader; if (triggerContext.TriggerAction == TriggerAction.Insert) { using (SqlConnection connection = new SqlConnection(@"context connection=true")) { connection.Open(); command = new SqlCommand(@"SELECT * FROM StoryItems", connection); reader = command.ExecuteReader(); reader.Read(); // get inserted value // ***********Here am trying to retrieve the location and name column value Location= (string)reader[9]; Name= (String) reader[9]; reader.Close(); try { // try to pass parameter to windows service WindowsService param = new WindowService(InsertedValue1, InsertedValue2); } catch (Exception ex) { } // Replace with your own code SqlContext.Pipe.Send("Trigger FIRED"); } } } } 

一些如何不喜欢列名,我不知道这里缺少什么。“Trigger_Web”是我的CLR SP名称。

首先,您需要在可视工作室中创建触发器应用程序。

文件 – >新建 – >项目 – >数据库 – >选择Visual C#CLR数据库项目。

它将提示您连接到数据库。 完成后,确保您的触发器应用程序在您喜欢的任何表上监听记录插入(您可以在此处阅读有关可视工作室中CLR应用程序的更多信息)。

从上面链接的步骤,添加一个触发器。 你的方法应该是这样的:

 [Microsoft.SqlServer.Server.SqlTrigger(Name = "GetTransaction", Target = "EvnLog", Event = "FOR INSERT")] public static void GetTransaction() { SqlCommand command; SqlTriggerContext triggerContext = SqlContext.TriggerContext; SqlPipe pipe = SqlContext.Pipe; SqlDataReader reader; if (triggerContext.TriggerAction == TriggerAction.Insert) { using (SqlConnection connection = new SqlConnection(@"context connection=true")) { connection.Open(); command = new SqlCommand(@"SELECT * FROM INSERTED", connection); reader = command.ExecuteReader(); reader.Read(); // get inserted value InsertedValue1 = (DateTime)reader[0]; InsertedValue2 = (string)reader[9]; reader.Close(); try { // try to pass parameter to windows service WindowsService param = new WindowService(InsertedValue1,InsertedValue2) } catch (Exception ex) { } } 

注意:GetTransaction是您要创建的触发器的名称,在这种情况下,Evnlog是表的名称

在SQL服务器中使用类似扩展存储过程的东西,调用C#类/可执行文件,然后可以执行该服务。

您还可以从表上on_insert事件的触发器调用命令行函数,该事件可以启动/停止服务,或运行exe或批处理文件。

一些想法: http : //www.sqlservercentral.com/Forums/Topic960855-392-1.aspx

和http://msdn.microsoft.com/en-us/library/ms189799.aspx