Why is a query significantly slower when executed in code than in SSMS?
Despite having the same query and execution environment, a query may exhibit a notable time difference when run in code compared to SQL Server Management Studio (SSMS). This question delves into the underlying causes for this discrepancy.
Investigating the Issue
The provided code comparison reveals a discrepancy in the data type of the @clientID parameter between the C# code and the SSMS script. In C#, the AddWithValue method adds the parameter as an NVARCHAR, while in SSMS, the parameter is declared as a VARCHAR.
Data Type Precedence and SARG-ability
Due to data type precedence rules, the Where client_id = @clientID expression becomes non-SARG-able (Search Argument) when @clientID is of type NVARCHAR, assuming the client_id column is of type VARCHAR. This forces the query optimizer to perform a costly table scan.
Solution
To resolve this discrepancy, either:
SqlParameter clientIDParam = new SqlParameter("@clientID", SqlDbType.Varchar, 200); clientIDParam.Value = ClientID; ada.SelectCommand.Parameters.Add(clientIDParam);
Where client_id = cast(@clientID as varchar(200))
Specifying the data type explicitly helps prevent potential cache pollution issues.
Further Considerations
By understanding these data type subtleties and implementing the recommended solutions, you can resolve the query performance discrepancy between code and SSMS.
The above is the detailed content of Why is My SQL Query Much Slower in Code Than in SSMS?. For more information, please follow other related articles on the PHP Chinese website!