Sql-server – OPTIMIZE FOR UNKNOWN in a Stored Procedure

execution-plansql serverstored-procedures

All the examples I've seen online imply that OPTIMIZE FOR UNKNOWN is applied on a specific query.

Can OPTIMIZE FOR UNKNOWN be applied to a stored procedure as a whole (and not just to a specific query)? If yes, what would be the syntax?

Best Answer

It is not possible to set OPTIMIZE FOR UNKNOWN at the stored procedure level in SQL Server. You could use WITH RECOMPILE, which I don't recommend using unless you are on SQL Server 2005 or lower, but it doesn't achieve the same thing. In my opinion, OPTIMIZE FOR UNKNOWN should be avoided. Spend the time to figure out why you are experiencing parameter sniffing. There could be a way to fix it without working around it. I prefer OPTIMIZE FOR @variable_name but have also had to resort to RECOMPILE at the query level.

This article may be helpful.