sql服务器的奇怪行为(查询时响应)
本文关键字:查询 响应 服务器 sql | 更新日期: 2023-09-27 18:30:04
我已经问了一个问题"超时过期,优化查询",有一段时间无法响应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
}
}
}
}
20000条记录需要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
}
}
}
}
我用不带SqlParameter
的发送值更改了@date
,我在0秒内得到了结果!!
对此结果有何建议
PS:
- 我们将数据库中的日期保存为字符串YYYYMMDD(PT.date是varchar(8))
- beginDate和enddate类似字符串(20130904)
如果查询的结构没有改变,并且使用相同的参数执行查询,那么SQL Server可能正在缓存查询的结果,请参阅此问题以了解类似的问题。