How can I cure parameter sniffing on SQL Server 2000?

烈酒焚心 提交于 2019-12-24 10:22:31

问题


I am having an issue where an update query with about 70 parameters times-out on occasion. Based on some research, I believe this is due to packet sniffing. I saw that in newer versions of SQL Server, I can use the Option(recompile) clause, but that does not work in my case, since I am using server 2000.

I am using sqlhelper.executeNonQuery and not a stored procedure.


回答1:


An easy fix is not to use parameters. Instead of:

SELECT * FROM YourTable WHERE UserName = @myUserName;

Pass:

SELECT * FROM YourTable WHERE UserName = 'PFranchise'

If SQL Server does not know about parameters, it can't sniff them! SQL Server will recompile the query plan for every query.

Two notes about this approach:

  • Be careful about SQL Injection
  • In later versions of SQL Server, the server option "forced parameterization" can sniff even queries without parameters. It's turned off by default. But it's something to keep in mind when you upgrade SQL Server.



回答2:


As far as I know there is no "out of the box" way like Option(recompile), however I remember I found a way to fool the optimizer. It seems to sniff only the parameter that you're actually PASSING externally to the query, not all of them. So, if you try to run

SELECT MyField1, MyField2 FROM MyTable WHERE MyOtherField = @MyParm

Parameter sniffing WILL happen, however if you write something like

DECLARE @MyUnsniffableParm varchar(30)
SET @MyUnsinffableParm = @MyParm    
SELECT MyField1, MyField2 FROM MyTable WHERE MyOtherField = @MyUnsniffableParm

ad of course pass to your script just the @MyParm parameter, parameter sniffing doesn't seems to happen! Let me know If I recall correctly I have no SQL 2000 instances to try!
EDIT:
Looks like something else is doing the same out here: http://blogs.msdn.com/b/khen1234/archive/2005/06/02/424228.aspx



来源:https://stackoverflow.com/questions/13144556/how-can-i-cure-parameter-sniffing-on-sql-server-2000

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