Why does the SqlServer optimizer get so confused with parameters?

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

    As indicated it be a compilation issue. Does this issue still occur if you revert the procedure? One thing you can try if this occurs again to force a recompilation is to use:

    sp_recompile [ @objname = ] 'object'

    Right from BOL in regards to @objname parameter:

    Is the qualified or unqualified name of a stored procedure, trigger, table, or view in the current database. object is nvarchar(776), with no default. If object is the name of a stored procedure or trigger, the stored procedure or trigger will be recompiled the next time that it is run. If object is the name of a table or view, all the stored procedures that reference the table or view will be recompiled the next time they are run.

    If you drop and recreate the procedure you could cause clients to fail if they try and execute the procedure. You will also need to reapply security settings.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-15 13:35

    Is there any chance that the parameter value being provided is sometimes not int?

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