Why does a parameterized query produces vastly slower query plan vs non-parameterized query

后端 未结 4 1440
萌比男神i
萌比男神i 2020-11-30 05:53

In a SQL Server 2005 database I\'m working on this query:

select *
from foo
join bar on bar.x = foo.x
join baz on baz.y = foo.

4条回答
  •  没有蜡笔的小新
    2020-11-30 06:19

    I think you're running afoul of "parameter sniffing". Basically, what this means is that SQL Server tries to use as much information as it has to calculate an optimal execution plan for your query. In the case of your first query, you have a constant value that is known at compile time, so the engine can directly optimize the query plan for that value.

    In the second one, the fact that you are using a variable masks that value from the engine at compile time (you'd think it should be able to figure it out, but I've actually had similar issues with a simple constant expression!), leading to poor performance.

    One way you can try to get around this would be to wrap the query in a stored procedure that takes the parameter directly and then applies it to the query -- something like this:

    CREATE PROCEDURE test
      @p0 int
    AS
    BEGIN
      select *
      from foo
      join bar on bar.x = foo.x
      join baz on baz.y = foo.y
      where foo.x = @p0
    END
    

    This should allow the optimizer to accurately "sniff" the parameter you use and generate an optimal query plan for you.

提交回复
热议问题