EF 4.1: Why does turning a constant into a variable result in extra sub query?

后端 未结 4 1117
失恋的感觉
失恋的感觉 2021-01-06 09:51

Today I discovered that Entity Framework was adding an unnecessary sub query to the SQL it generates. I started digging my code trying to narrow down where it might come fro

4条回答
  •  长情又很酷
    2021-01-06 10:03

    NOT an answer to the question - just context on using Parameters.

    This is to do with creating a query such that it will re-use existing query plans.

    If you inject the variable (as opposed to a reference to a parameter) into the generate SQL, then SQL Server (and probably other database engines) will not be able to re-use the same plan when the variable changes.

    For constants this is not an issue, because you know the value is always the same, but for variables each time the query is executed the SQL and thus query plan would be slightly different.

    This might not sound like much, but SQL only has a certain amount of space assigned for query plans, so having hundreds/thousands of minor variations in the cache is a real 'waste of space' so to speak!

提交回复
热议问题