Why does the SqlServer optimizer get so confused with parameters?

后端 未结 9 2520
猫巷女王i
猫巷女王i 2020-12-15 12:59

I know this has something to do with parameter sniffing, but I\'m just perplexed at how something like the following example is even possible with a piece of technology that

9条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-15 13:22

    The 1 in 10 gives the wrong plan that is cached.

    RECOMPILE adds an overhead, masking allows each parameter to be evaluated on it's own merits (very simply).

    By wrong plan, what if the 1 in 10 generates an scan on index 1 but the other 9 produce a seek on index 2? eg, the 1 in 10 is, say, 50% of the rows?

    Edit: other questions

    • Known issue?: SQL Server 2005 stored procedure fails to complete with a parameter
    • Stored Procedure failing on a specific user

    Edit 2:

    Recompile does not work because the parameters are sniffed at compile time.
    From other links (pasted in):

    This article explains...

    ...parameter values are sniffed during compilation or recompilation...
    

    Finally (edit 3):

    Parameter sniffing was probably a good idea at the time and probably works well mostly. We use it across the board for any parameter that will end up in a WHERE clause. We don't need to use it because we know that only a few (more complex eg reports or many parameters) could cause issues but we use it for consistency.

    And the fact that it will come back and bite us when the users complain and we should have used masking...

提交回复
热议问题