SQL Query Using Entity Framework Runs Slower, uses bad query plan

前端 未结 1 1664
遥遥无期
遥遥无期 2021-02-15 10:05

am using entity framework generally successfully, but one query is running remarkably slowly. The query (generated by EF) is as follows:

exec sp_executesql N\'S         


        
1条回答
  •  北恋
    北恋 (楼主)
    2021-02-15 10:54

    The problem was a stale or incorrect query plan for my query.

    I solved the problem for deleting the existing query plans for this query.

    Thanks to Vladimir Baranov for pointing me at sommarskog.se/query-plan-mysteries.html. Thanks also to tschmit007 and annemartijn.

    I had to identify the query plans for my query in the database using the following query:

    SELECT qs.plan_handle, a.attrlist, est.dbid, text
    FROM   sys.dm_exec_query_stats qs
    CROSS  APPLY sys.dm_exec_sql_text(qs.sql_handle) est
    CROSS  APPLY (SELECT epa.attribute + '=' + convert(nvarchar(127), epa.value) + '   '
              FROM   sys.dm_exec_plan_attributes(qs.plan_handle) epa
              WHERE  epa.is_cache_key = 1
              ORDER  BY epa.attribute
              FOR    XML PATH('')) AS a(attrlist)
     WHERE  est.text LIKE '%standardHourRate%' and est.text like '%q__7%'and est.text like '%Unit Overhead%'
     AND  est.text NOT LIKE '%sys.dm_exec_plan_attributes%'
    

    This is a lightly modified version of the query from sommarskog's paper. Note that you have to put your own code in the like statements to find your query. This query responds with the attribute list and the plan handle for each query plan for my query.

    I tried to figure out which plan came from SSMS and which from EF, so I deleted all of them, using the following syntax:

    dbcc freeproccache([your plan handle here])
    

    The new plan created for my EF query worked perfectly. Apparently, the EF plan did not take into consideration that I had updated statistics on the database recently. Unfortunately, I don't know how to do a sp_recompile for an EF query.

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