情况:c#,sql 2000
我有一个表,我们称它为“我的表”,其中包含 3000 万行。 主键由字段 A 和 B 组成:
A char(16)
B smallint(2)
当我进行这样的搜索时,它运行得非常慢(例如,它进行全表扫描)
string a="a";
int b=1;
string sql = "select * from table(nolock) where a=@a and b=@b";
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()) {...}
}
这到底是怎么回事?我觉得很奇怪。
最佳答案
参数和列的数据类型是否匹配?他们看起来不是这样datatype precedence适用
该列是 smallint,但您发送的是 int。该列将转换为 int,因为它具有更高的优先级。所以它不会使用索引。
关于c# - 为什么参数比 where 子句中的文字值慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1392307/