SQL Server performance issue with parameters

限于喜欢 提交于 2019-12-14 04:19:29

问题


There is a performance issue with a SQL query. This is my query

declare @siteId int,    
@totalCount int

 SELECT @totalCount = COUNT(DISTINCT pro.product_id)
    FROM product AS pro 
    INNER JOIN product_to_category AS proCat ON pro.product_id = proCat.product_id
    INNER JOIN product_to_vendor proVen ON  pro.product_id = proVen.product_id
WHERE pro.site_id = @siteId 
    AND pro.product_type <> 3
print @totalCount

It is take 6 seconds to execute..

when I remove parameters as follows

@totalCount int

SELECT @totalCount = COUNT(DISTINCT pro.product_id)
FROM product AS pro 
INNER JOIN product_to_category AS proCat ON pro.product_id = proCat.product_id
INNER JOIN product_to_vendor proVen ON  pro.product_id = proVen.product_id
WHERE pro.site_id = 28
AND pro.product_type <> 3
print @totalCount

and execute query again, it takes only 2 seconds.

is there a method to improve performance of an query like this? why it takes time to assign values to parameters? any comments....


回答1:


This is not a parameter it is a variable.

SQL Server does not sniff the values of variables so it does not know at compile time that the value it will contain is 28

Add OPTION (RECOMPILE) to the end of your query to get it to recompile the statement after the variable's value has been assigned and it should generate a more suitable execution plan.



来源:https://stackoverflow.com/questions/8415999/sql-server-performance-issue-with-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!