从代码调用的存储过程超时,从 SSMS 执行正常

Stored procedure timesout called from code, executes ok from SSMS

我有一个存储过程,当从 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 使用相同的参数值调用存储过程时,它会正确执行。

可能你忘了指定参数的方向,因为你可以提供输入输出参数。试试这个是否有效:

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

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

cmd.CommandTimeout = 0;

Note :
Your query execution will takes infinitive time.