这样我们就可以通过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表,然后我们可以像这样编写sql
SELECT 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());
}
如果我要向错误的方向监控多个表数据的变化,那么请指导我正确的信息。寻找建议。感谢
答案 0 :(得分:4)
这里有非常好的文章,包含源代码
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);
}