concept bad parameter sniffing in category sql

appears as: bad parameter sniffing
SQL Server MVP Deep Dives Vol. 2

This is an excerpt from Manning's book SQL Server MVP Deep Dives Vol. 2.

There isn’t a single correct answer to that question. As I stated at the beginning of this chapter, statistics drive execution plans and data drives statistics. In this case, there’s a wide divergence in the data stored in the Address table. The index in question on the City column mostly has only a few entries for each city. 'Mentor' is typical of the average value in the index. 'London' is an outlier. Each set of returned data is best retrieved by a different execution plan. This wide divergence is what’s causing two different plans to be created. The right plan is the one that’s best for the majority of your data. But getting that plan all the time can be hard, as you’ve seen. It’s important that you get the right plan because once it’s created, it’ll be cached so each subsequent query run against the system will use that plan. So how do you deal with bad parameter sniffing?

Another popular method for addressing the issue of bad parameter sniffing is to recompile the statement every time it runs. This makes sure that, regardless of the values of the parameters passed you get a new execution plan each and every time the stored procedure is called. If you modify the original procedure as follows, the statement will be recompiled every time it executes:

ALTER PROC dbo.spAddressByCity @City NVARCHAR(30)
AS
    SELECT  a.AddressID,
            a.AddressLine1,
            a.AddressLine2,
            a.City,
            sp.[Name] AS StateProvinceName,
            a.PostalCode
    FROM    Person.Address AS a
            JOIN Person.StateProvince AS sp
            ON a.StateProvinceID = sp.StateProvinceID
    WHERE   a.City = @City
    OPTION  (RECOMPILE) ;

Now if you execute the stored procedure with the parameters you’ve been using, the execution plan will be different for each parameter. The Compile Value in the parameter list will be different each time as well. This approach won’t work if there are multiple statements within the procedure that are all suffering from bad parameter sniffing. In this case you’d want to modify the code so that the entire procedure recompiles instead of just the statement: