Parameter Sniffing (or Spoofing) in SQL Server

FYI – you need to be aware of something else when you’re working with SQL 2005 and stored procs with parameters.

SQL Server will compile the stored proc’s execution plan with the first parameter that’s used. So if you run this:

usp_QueryMyDataByState 'Rhode Island'

The execution plan will work best with a small state’s data. But if someone turns around and runs:

usp_QueryMyDataByState 'Texas'

The execution plan designed for Rhode-Island-sized data may not be as efficient with Texas-sized data. This can produce surprising results when the server is restarted, because the newly generated execution plan will be targeted at whatever parameter is used first – not necessarily the best one. The plan won’t be recompiled until there’s a big reason to do it, like if statistics are rebuilt.

This is where query plans come in, and SQL Server 2008 offers a lot of new features that help DBAs pin a particular query plan in place long-term no matter what parameters get called first.

My concern is that when you rebuilt your stored proc, you forced the execution plan to recompile. You called it with your favorite parameter, and then of course it was fast – but the problem may not have been the stored proc. It might have been that the stored proc was recompiled at some point with an unusual set of parameters and thus, an inefficient query plan. You might not have fixed anything, and you might face the same problem the next time the server restarts or the query plan gets recompiled.

Leave a Comment