首先要啟用Service Broker
ALTER DATABASE 數據庫名稱 SET NEW_BROKER WITH ROLLBACK IMMEDIATE; ALTER DATABASE 數據庫名稱 SET ENABLE_BROKER;
然后sql語句必須是依賴是基於某一張表的,而且查詢語句只能是簡單查詢語句,不能帶top或*,同時必須指定所有者,即類似[dbo].[]
static void Main(string[] args) { SqlDependency.Start(connectionString);//傳入連接字符串,啟動基於數據庫的監聽 UpdateGrid(); Console.Read(); SqlDependency.Stop(connectionString); } static string connectionString = "Server=ADMIN-PC;Database=newsData;User Id=sa;Password=123456"; private static void UpdateGrid() { using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); using (SqlCommand command = new SqlCommand("SELECT id,cemskind FROM [dbo].[op_weight_cemskind]", connection)) { command.CommandType = CommandType.Text; SqlDependency dependency = new SqlDependency(command); dependency.OnChange += new OnChangeEventHandler(dependency_OnChange); using (SqlDataReader sdr = command.ExecuteReader()) { Console.WriteLine(); while (sdr.Read()) { Console.WriteLine("ID:{0}\t數據:{1}\t", sdr["id"].ToString(), sdr["cemskind"].ToString()); } sdr.Close(); } } } } private static void dependency_OnChange(object sender, SqlNotificationEventArgs e) { if (e.Type == SqlNotificationType.Change) //只有數據發生變化時,才重新獲取並數據 { UpdateGrid(); } }
監聽結果