这样,我们通过sql依赖项监视表数据更改。
private static void RegisterNotification()
{
try
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT ID, Name FROM dbo.TestTable";
dep = new SqlDependency(cmd);
dep.OnChange += new OnChangeEventHandler(OnDataChange);
SqlDataReader dr = cmd.ExecuteReader();
{
while (dr.Read())
{
Console.WriteLine("Name = " + dr[1].ToString());
}
}
dr.Close();
Console.WriteLine("Waiting for any data changes...\nPress to end program.");
Console.ReadLine();
}
}
finally
{
//SqlDependency.Stop(connStr);
}
}
这样,我们为表更改指定sql
SELECT ID, Name FROM dbo.TestTable
。我想知道是否需要监视2个表,然后我们可以像这样编写sqlSELECT ID, Name FROM dbo.TestTable1;SELECT ID, Name FROM dbo.TestTable2
并以这种方式读取表数据
SqlDataReader dr = cmd.ExecuteReader();
{
while (dr.Read())
{
Console.WriteLine("Name = " + dr[1].ToString());
}
}
然后再次
dr.NextResult()
并再次阅读 while (dr.Read())
{
Console.WriteLine("Name = " + dr[1].ToString());
}
如果我要去错误的方向来监视多个表数据的变化,那么请以正确的信息指导我,以寻求建议。谢谢
最佳答案
这里非常好的文章,带有源代码
与SQL Server,LINQ和ASP.NET 3.5的SQL缓存依赖关系
http://www.dotnetcurry.com/showarticle.aspx?ID=263
重要(摘自文章)
GRANT SUBSCRIBE QUERY NOTIFICATIONS TO "TESTSERVER\ASPNET"
C#
protected void Application_Start(object sender, EventArgs e)
{
SqlDependency.Start(ConfigurationManager.ConnectionStrings["pubsConnectionString"].ConnectionString);
}
以下代码也停止了侦听器:
protected void Application_End(object sender, EventArgs e)
{
SqlDependency.Stop(ConfigurationManager.ConnectionStrings["pubsConnectionString"].ConnectionString);
}
关于c# - 如何使用SqlDependency监视2或3表数据更改,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25488946/