I have a fairly simple query that I keep getting timeouts (it takes over three minutes to complete, I stopped it early so I could post this question) on when it is running i
Capture the execution plan from both SSMS when you manually run your query and then from Profiler when you are running your application. Compare and contrast.
Your code in SSMS is not the same code you run in your application. This line in your application adds a NVARCHAR parameter:
ada.SelectCommand.Parameters.AddWithValue("@clientID", ClientID);
while in the SSMS script you declare it as VARCHAR:
declare @clientID varchar(200)
Due to the rules of Data Type Precedence the Where client_id = @clientID
expression in your query is not SARG-able where @clientID
is of type NVARCHAR (I'm making a leap of faith and assume that client_id
column is of type VARCHAR). The application thus forces a table scan where the SSMS query can do a quick key seek. This is a well know and understood issue with using Parameters.AddWithValue and has been discussed in many articles before, eg. see How Data Access Code Affects Database Performance. Once the problem is understood, the solutions are trivial:
add parameters with the constructor that accepts a type: Parameters.Add("@clientID", SqlDbType.Varchar, 200)
(and do pass in the explicit length to prevent cache pollution, see Query performance and plan cache issues when parameter length not specified correctly
or cast the parameter in the SQL text: where client_id = cast(@clientID as varchar(200))
.
The first solution is superior because it solves the cache pollution problem in addition to the SARG-ability problem.
I would also recommend you read Slow in the Application, Fast in SSMS? Understanding Performance Mysteries
Run the profiler on your c# connection - there may be other activity going on that you are not aware of.
Run DBCC FREEPROCCACHE
, as suggested here, just to make sure the problem isn't due to a stale query execution plan.