在SQL Server中搜索当前日期的数据
为什么在SQL Server中第一个查询比第二个查询花费的时间少 完成此查询需要4秒钟:在SQL Server中搜索当前日期的数据,sql,sql-server,Sql,Sql Server,为什么在SQL Server中第一个查询比第二个查询花费的时间少 完成此查询需要4秒钟: select * from salesinvmaster where day(salesdate) = day(getdate()) and month(salesdate) = month(getdate()) and year(salesdate) = year(getdate()) 此查询需要10秒钟: select * from salesinvmaster where s
select *
from salesinvmaster
where day(salesdate) = day(getdate()) and
month(salesdate) = month(getdate()) and
year(salesdate) = year(getdate())
此查询需要10秒钟:
select *
from salesinvmaster
where salesdate between '2017-11-01 00:00:00' and '2017-11-01 23:59:59'
检查查询的执行计划,我想我们已经在日期上进行了隐式转换!检查这个
这两个查询是不同的,因为今天是12月的某一天,而不是11月1日 我的猜测是,
salesdate
列上没有索引,并且第一个查询返回的行数更少,因此看起来更快。为了记录在案,我建议将逻辑编写为以下之一:
where convert(date, salesdate) = convert(date, getdate())
where salesdate >= convert(date, getdate()) and
salesdate < dateadd(day, 1, convert(date, getdate()))
其中convert(date,salesdate)=convert(date,getdate())
其中salesdate>=转换(日期,getdate())和
salesdate
请注意,SQL Server使用索引将日期/时间值转换为日期。这是函数不阻止使用索引的罕见(仅?)情况之一
至于第二种方法,它不需要包含值的时间成分。您是否查看了两个查询的查询计划?看起来您没有在
saledate
上定义索引。如果您这样做,那么第二个查询应该运行得非常快。如果您使用的是datetime,那么第二个查询将在23:59:59毫秒以上的时间内删除所有行。您应该真正使用=
和