Stored procedure timesout called from code, executes ok from SSMS

1.1k views Asked by At

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.

2

There are 2 answers

0
shA.t On BEST ANSWER

To avoid that error just use:

cmd.CommandTimeout = 0;

Note :
Your query execution will takes infinitive time.

0
LInsoDeTeh On

Maybe you forgot to specify the direction of the parameter, as you can provide input and output parameters. Try if this works:

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