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