declare @sql nvarchar(1024)
set @sql = 'select * from customer where lastName = @lastName'
exec sp_executesql @sql, '@lastName nvarchar(80)' , 'Zz'
Suppose the customer has index on lastName. There is no lastName = 'Zz'. Sql will choose the index seek on the table. And cached the execute plan.
Then if the value of lastName changed in next execution, such as:
exec sp_executesql @sql, '@lastName nvarchar(80)' , 'Smith'
Suppose the customer has 1MM records with lastName = 'Smith'. Then the performance will be very bad becase it will use the cached plan by index seek.
We can change it:
set @sql = @sql = ' option (recompile)'
exec sp_executesql @sql, '@lastName nvarchar(80)' , 'Smith'
Then SQL server will recompile the query. It will choose the primary key index scan which is better.
No comments:
Post a Comment