1、使用下面语句启用数据库的 Service Broker 

ALTER DATABASE [YOUR DBNAME] SET NEW_BROKER WITH ROLLBACK IMMEDIATE;
ALTER DATABASE [YOUR DBNAME] SET ENABLE_BROKER;

2、使用SqlDependency.Start(connString)静态方法启用监听

public string connString;

private string SqlMonitorCmd;

public SQLHelper(bool SqlMonitorEnable, string sqlMonitorCmd, string ConnString)
{
    connString = ConnString;
    SqlMonitorCmd = sqlMonitorCmd;
    if (SqlMonitorEnable && !string.IsNullOrEmpty(SqlMonitorCmd) && !string.IsNullOrEmpty(connString))
    {
        SqlDependency.Start(connString);
        SqlMonitor();
    }
}

3、创建监听方法,绑定sqlCommand

private void SqlMonitor()
{
       using (SqlConnection connection = new SqlConnection(connString))
       {
                connection.Open();
                //依赖是基于某一张表的,而且查询语句只能是简单查询语句,不能带top或*,同时必须指定所有者,即类似[dbo].[]
                using (SqlCommand command = new SqlCommand(SqlMonitorCmd, connection))
                {
                    command.CommandType = CommandType.Text;
                    SqlDependency sqlDependency = new SqlDependency(command);
                    sqlDependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
                    command.ExecuteReader();
                }
        }
}

  private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
  {
         if (e.Type == SqlNotificationType.Change) //只有数据发生变化时,才重新获取并数据
         {
             SqlChanged?.Invoke();
             SqlMonitor();//由于OnChange只能触发一次,所以要重新绑定
         }
  }

 

注:

连接数据库尽量使用sql用户名sa连接,不要用win身份登录,如果OnChange始终不能触发,可能是用户权限不够使用这个语句赋予权限
ALTER AUTHORIZATION ON DATABASE::[YOUR DBNAME] TO sa;

12-27 00:17
查看更多