情况:c#,sql 2000为什么参数在where子句中比字面值慢?
我有一张桌子,我们称之为'mytable',有三千万行。 主键是由域A和B的了:
A char(16)
B smallint(2)
当我做这样的搜索,它运行非常缓慢(如它做了全表)
string a="a";
int b=1;
string sql = "select * from table(nolock) where [email protected] and [email protected]";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("@a", a);
cmd.Parameters.AddWithValue("@b", b);
using (SqlDataReader rdr = cmd.ExecuteReader()) {...}
}
将其更改为然而,它运行得非常快(例如它触及索引):
string where =
String.Format("a='{0}' and b={1}", a, b);
string sql = "select * from table(nolock) where " + where;
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
using (SqlDataReader rdr = cmd.ExecuteReader()) {...}
}
究竟是怎么回事?对我来说似乎很陌生。
尝试重新启动数据库服务器并颠倒测试顺序。所有这些的目标是排除SQL Server部分的缓存。 – 2009-09-08 06:38:16
不幸的是不是生产服务器的选项。 – Chris 2009-09-08 06:39:09
这可能会有所帮助 - 但可能不会:http://stackoverflow.com/questions/1211287/getting-a-query-to-index-seek-rather-than-scan – PaulB 2009-09-08 06:41:02