0

我已经问了一个问题“超时已过期,优化查询”,有一段时间为我的查询响应 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)
4

1 回答 1

0

如果您的查询在结构上没有改变并且您正在使用相同的参数执行它,那么 SQL Server 可能正在缓存您的查询结果,请参阅此问题以了解类似问题。

于 2013-09-04T10:21:23.840 回答