Why does the SqlServer optimizer get so confused with parameters?

后端 未结 9 2524
猫巷女王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:35

    I know this is a 2 year old thread, but it might help someone down the line.

    Once you analyze the query execution plans and know what the difference is between the two plans (query by itself and query executing in the stored procedure with a flawed plan), you can modify the query within the stored procedure with a query hint to resolve the issue. This works in a scenario where the query is using the incorrect index when executed in the stored procedure. You would add the following after the table in the appropriate location of your procedure:

    SELECT col1, col2, col3
    FROM YourTableHere WITH (INDEX (PK_YourIndexHere))
    

    This will force the query plan to use the correct index which should resolve the issue. This does not answer why it happens but it does provide a means to resolve the issue without worrying about copying the parameters to avoid parameter sniffing.

提交回复
热议问题