【问题标题】:Stored procedure timesout called from code, executes ok from SSMS从代码调用存储过程超时,从 SSMS 执行正常
【发布时间】:2015-06-10 07:25:54
【问题描述】:

我有一个存储过程,当从 SSMS 调用并成功执行时,它需要大约 10 秒才能运行。该过程将int 作为参数。

当从代码调用相同的存储过程时:

using (var connection = new SqlConnection(ConnectionStringName))
{
    using (var cmd = new SqlCommand("ProcedureName", connection))
    {
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.Add(new SqlParameter("@itemId", itemId));
        cmd.CommandTimeout = 150;

        connection.Open();
        cmd.ExecuteNonQuery(); 
    }
} 

我得到的错误如下:

System.Data.SqlClient.SqlException (0x80131904): Timeout expired.  
The timeout period elapsed prior to completion of the operation or the server is not responding. ---> 
System.ComponentModel.Win32Exception (0x80004005): The wait operation timed out

传递的参数是有效的,当使用相同的参数值从SSMS调用存储过程时,它会正确执行。

【问题讨论】:

  • 从 SSMS 执行需要多长时间?
  • @shA.t 删除了那行,我得到了同样的异常,只是更快。
  • 通过使用cmd.CommandTimeout = 0;,您将永远不会看到该错误,但您的问题出在需要修改的存储过程内部;)。
  • 确实,设置 cmd.CommandTimeout = 0 可以解决问题,我会将其标记为答案。但是,调用 SP 的执行时间大约需要 30 秒,远远超过从 SSMS 调用它。有什么建议吗?
  • 我建议你问另一个问题并添加存储过程的代码来优化它(或检查this);)。

标签: c# sql-server stored-procedures connection-timeout


【解决方案1】:

为避免该错误,只需使用:

cmd.CommandTimeout = 0;

注意:
您的查询执行将花费无限时间。

【讨论】:

    【解决方案2】:

    也许你忘了指定参数的方向,因为你可以提供输入和输出参数。试试这是否可行:

    SqlParameter param = new SqlParameter("@itemId", itemId);
    param.Direction = ParameterDirection.Input;
    cmd.Parameters.Add(param);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-28
      • 1970-01-01
      • 2011-03-02
      相关资源
      最近更新 更多