Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Very different execution times of SQL query in C# and SQL Server Management Studio

I have a simple SQL query that when run from C# takes over 30 seconds then times-out every time, whereas when run on SQL Server Management Studio successfully completes instantly. In the latter case, a query execution plan reveals nothing troubling, and the execution time is spread nicely through a few simple operations.

I've run 'EXEC sp_who2' while the query is running from C#, and it is listed as taking 29,000 milliseconds of CPU time, and is not blocked by anything.

I have no idea how to begin solving this. Does anyone have some insight?

The query is:

SELECT
    c.lngId,
    ...
FROM tblCase c
    INNER JOIN tblCaseStatus s ON s.lngId = c.lngId
    INNER JOIN tblCaseStatusType t ON t.lngId = s.lngId
    INNER JOIN [Another Database]..tblCompany cm ON cm.lngId = cs.lngCompanyId
WHERE t.lngId = 25
    AND c.IsDeleted = 0
    AND s.lngStatus = 1
like image 847
Paul Avatar asked Jun 18 '10 14:06

Paul


1 Answers

To start with, extract the query plan of the query when is run from C#:

select p.query_plan, *
from sys.dm_exec_requests r
cross apply sys.dm_exec_query_plan(r.plan_handle) p
where r.session_id = <spid of C# connection>

Then compare it with the plan executed under the SSMS session (simply click the Show actual plan in toolbar).

And, as a general rule, always try to apply a methodical approach rather than guess. Wait and Queues is a very good, proven, performance troubleshooting methodology for SQL Server.

like image 88
Remus Rusanu Avatar answered Sep 23 '22 03:09

Remus Rusanu