Query extremely slow in code but fast in SSMS

前端 未结 4 1777
无人及你
无人及你 2020-11-27 07:00

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

相关标签:
4条回答
  • 2020-11-27 07:46

    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.

    0 讨论(0)
  • 2020-11-27 07:48

    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

    0 讨论(0)
  • 2020-11-27 08:01

    Run the profiler on your c# connection - there may be other activity going on that you are not aware of.

    0 讨论(0)
  • 2020-11-27 08:06

    Run DBCC FREEPROCCACHE, as suggested here, just to make sure the problem isn't due to a stale query execution plan.

    0 讨论(0)
提交回复
热议问题