开发者

Query is slow, becomes fast after "dbcc freeproccache". Could it be my parameters?

The web-site in question usually performs pretty good, but over time it becomes slower and slower.

We have a huge query to find the products that the user is searching for, and they are mostly in this form:

WHERE ProductName LIKE @ProductName OR @Product开发者_高级运维Name IS NULL
  AND ProductGroup LIKE @ProductGroup or @ProductGroup IS NULL
  AND (...)

That way we do not have to pass all the parameters if we are searching for only the Product Number. Could this be the reason that the queries are getting slower? Something to do with that the query is cached the first time, and the next time, when the parameters has changed, it uses the old query plan?

If so; What would be the best way to fix this? Dynamic SQL?


From the small snippet of the query you have shown it is difficult to see whether you are likely to have a Parameter sniffing issue but it sounds like it if you suddenly get a better plan after freeing the cache

But that is generally a bad way of writing queries anyway. (WHERE x=@x OR @X IS NULL type of query) as it leads to an unnecessary scan. It might not make any difference in this case dependant on whether your LIKE has a leading wildcard or not.

But SQL Server can convert the LIKE into a range seek on an index anyway so you will be unnecessarily penalising queries without a leading wildcard. (e.g. compare the plans for the queries below)

DECLARE @T nchar(3) 
SET @T='%f'


SELECT [name]
  FROM [master].[dbo].[spt_values]
where type like @T


SELECT [name]
  FROM [master].[dbo].[spt_values]
where type like @T OR @T IS NULL

Query is slow, becomes fast after "dbcc freeproccache". Could it be my parameters?

You could try splitting these cases out or generating the dynamic search conditions with dynamic SQL.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜