【问题标题】:SQL dependency using stored procedure使用存储过程的 SQL 依赖
【发布时间】:2015-10-05 13:22:49
【问题描述】:

我在 C# 代码中使用 SqlDependency 来提醒我的应用程序,当数据库中某一行的特定列值发生变化时。我可以使用内联 SQL 来实现它。

我想用存储过程替换它,但由于某种原因,代码没有执行存储过程。我正在从我的应用程序中粘贴几行代码。请告诉我如何修改它,以便我可以将内联 SQL 替换为过程调用来实现相同的效果。

var con = new SqlConnection(ConnectionString);
SqlDependency.Stop(con.ConnectionString);
SqlDependency.Start(con.ConnectionString);

var connection = new SqlConnection(con.ConnectionString);
connection.Open();

try
{
    using (var command = new SqlCommand("inlinesql", connection))
    {
        var dependency = new SqlDependency(command);
        dependency.OnChange += new OnChangeEventHandler(OnDependencyChange);

        using (SqlDataReader rdr = command.ExecuteReader())
        {
            try
            {
                if (rdr.HasRows)
                {
                    _autoEvent.WaitOne();
                }
                else
                {
                    continue;
                }
            }
            finally
            {
                rdr.Close();
            }
        }
    }
}
finally
{
    connection.Close();
    SqlDependency.Stop(con.ConnectionString);
}

void OnDependencyChange(object sender, SqlNotificationEventArgs e)
{
    dosomething();
}

【问题讨论】:

  • 以下答案对您有用吗?如果有,请标记为答案。谢谢!

标签: c# sql sql-server


【解决方案1】:

以上var dependency...放:

command.CommandType = CommandType.StoredProcedure;

并将inlinesql 替换为存储过程的名称。

【讨论】:

    【解决方案2】:

    对我有用的示例代码:

    using (var sqlConnection = new SqlConnection (_connectionString)) {
      sqlConnection.Open ();
      using (var sqlCommand = sqlConnection.CreateCommand ()) {
        sqlCommand.Parameters.Clear ();
        sqlCommand.CommandType = System.Data.CommandType.StoredProcedure;
        // YOUR STORED PROCEDURE NAME AND PARAMETERS SHOULD COME HERE
        sqlCommand.CommandText = "sp_InsertData";
        sqlCommand.Parameters.AddWithValue ("@Code", e.Entity.Symbol);
        sqlCommand.Parameters.AddWithValue ("@Name", e.Entity.Name);
        sqlCommand.Parameters.AddWithValue ("@Price", e.Entity.Price);
    
        try {
          var sqlDataInsert = sqlCommand.ExecuteNonQuery ();                    
        } catch (Exception ex) {
           MessageBox.Show (ex.Message, this.Title);
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多