sql server奇怪的行为(查询时间响应)

时间:2013-09-04 10:05:15

标签: c# sql-server

我已经问了一个问题"Timeout expired, optimize query"有问题一段时间来回复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)

1 个答案:

答案 0 :(得分:0)

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