我已经问了一个问题“超时已过期,优化查询”,有一段时间为我的查询响应 sql server:
using (SqlConnection sqlConn = new SqlConnection(SqlServerMasterConnection))
{
if (sqlConn.State != ConnectionState.Open) sqlConn.Open();
using (SqlCommand cmd = new SqlCommand("select DT.* from DetailTable DT, BillTable BT, PackageTable PT
where PT.Id= BT.IdPackage and DT.IdBill= BT.Id
and PT.CodeCompany = @codeCompany and PT.Date between @begin and @end",
sqlConn))
{
cmd.Parameters.Add(new SqlParameter(@begin , beginDate));
cmd.Parameters.Add(new SqlParameter("@end", endDate));
cmd.Parameters.Add(new SqlParameter("@codeCompany", codeCompany));
using (DbDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
//work todo
}
}
}
}
20,000 条记录需要 28 秒,
我写这个的奇怪行为
using (SqlConnection sqlConn = new SqlConnection(SqlServerMasterConnection))
{
if (sqlConn.State != ConnectionState.Open) sqlConn.Open();
using (SqlCommand cmd = new SqlCommand("select DT.* from DetailTable DT, BillTable BT, PackageTable PT where PT.Id= BT.IdPackage and DT.IdBill= BT.Id
and PT.CodeCompany = @codeCompany and PT.Date between '" + beginDate + "' and '" + endDate + "'"
,sqlConn))
{
cmd.Parameters.Add(new SqlParameter("@codeCompany", codeCompany));
using (DbDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
//work todo
}
}
}
}
我改变@date
了发送的值,没有SqlParameter
,我在 0 秒内得到了结果!
对此结果的任何建议
PS:
- 我们将数据库中的日期保存为字符串 YYYYMMDD(PT.Date 是一个 varchar(8))
- beginDate 和 enddate 是字符串,如 (20130904)