I run into the classic Parameter Sniffing issues in SQL Server 2012. Based on some research I found multiple options around this problem. The two options that I need to understand the difference between are OPTION(OPTIMIZE FOR UNKNOWN) vs OPTION(RECOMPILE).
I am hesitating to use OPTION(RECOMPILE) at the end of my queries that are having this issue because it will force the server to generate a new execution plan each time. If I call this query often this will spike up the CPU of that machine.
So that I use he best available solution, what are the real differences between the two options?
Will OPTION(OPTIMIZE FOR UNKNOWN) reuse cache instead of recompiling each time?
I have used both.
OPTION(OPTIMIZE FOR UNKNOWN)was used for a heavy search stored procedure that took in a variety of parameters. There were certain conditions, unknown to me (statistics and what not), that would throw the optimization off, the query was mundane, however, it would cause serious delays (and even time out).OPTION(OPTIMIZE FOR UNKNOWN)solved this issue but was not ideal.The same heavy search procedure would have intermittent issues, meaning after a few months, the search would time out. The immediate solution would be to call
sp_recompile, which is synonymous to adding aOPTION(RECOMPILE)clause to the stored procedure.The guts of the stored procedure propelled a "result as you type" solution in which every three keystrokes would trigger a DB search and the results would populate in a dropdown.
In the end, I removed the
OPTION(OPTIMIZE FOR UNKNOWN)and just simply added aEXEC sp_recompile<sp>to my nightly maintenance job and that resolved all issues.