【问题标题】:TSQL datetimes functions in where clausewhere 子句中的 TSQL 日期时间函数
【发布时间】:2013-11-24 11:29:57
【问题描述】:

我必须对托管在 MSSQL 服务器中的数据库表进行查询。

查询如下:

select *
from tableA
where createdOn between @startDate and @endDate

变量@startDate 和@endDate 的类型是日期时间。如果@endDate 等于当前日期并且@startDate 等于前一个月的日期,我认为我们可以将查询设为

declare @startDate datetime
declare @endDate datetime

set @startDate = DATEADD(month,-1,GETDATE())
set @endDate = GETDATE()


select *
from tableA
where createdOn between @startDate and @endDate

或作为

select *
from tableA
where createdOn between DATEADD(month,-1,GETDATE()) and GETDATE()

我认为第一个查询会比第二个查询更快,因为在第二个查询中我们调用 where 子句中的函数。我写了我的查询的两个版本,我也执行了它们。但是,我没有注意到性能上有任何显着差异。

谁能解释一下为什么我没有看到任何变化。也许认为第一个查询应该比第二个查询更快的想法是错误的。请让我知道,id是这样,为什么是错误的。

提前感谢您的帮助。

【问题讨论】:

    标签: performance tsql datetime


    【解决方案1】:

    查询优化器。

    查询优化器使两个查询相同。它知道 GETDATE() 对于所有测试都是相同的,因此可以优化调用。

    在此处阅读:Query Optimiser Deep DiveQuery Optimiser 以获得比您想要的更多的信息 :-)

    【讨论】:

      猜你喜欢
      • 2010-12-29
      • 2023-03-21
      • 1970-01-01
      • 2017-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多