Search code examples
c#sql-serverstored-proceduresconnection-timeout

Stored procedure timesout called from code, executes ok from SSMS


I have stored procedure which takes around 10 seconds to run when called from SSMS and executes successfully. The procedure takes an int as a parameter.

When calling the same stored procedure from code:

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(); 
    }
} 

The error I get is the following:

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

The passed parameter is valid and when calling the stored procedure from SSMS with the same parameter value it executes correctly.


Solution

  • To avoid that error just use:

    cmd.CommandTimeout = 0;
    

    Note :
    Your query execution will takes infinitive time.