且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将datetime与SQL Server中的日期进行比较

更新时间:2022-10-18 09:32:27

不要试图做这样的事情:

 从[User] U中选择*,其中convert(varchar(10),U.DateCreated,120)='2014-02-07'

这是一个更好的方法:

 从[用户] U $ b $中选择* b其中U.DateCreated> ='2014-02-07'和U.DateCreated dateadd(day,1,'2014-02-07')

请参阅: Sargable



EDIT +
有2个基本避免在where子句(或连接条件)中使用数据的功能的原因。


  1. 在大多数情况下,使用数据的函数过滤器或连接消除了优化器访问该字段的索引的能力,因此使查询更慢(或更昂贵)。

  2. 另一个是针对每一行数据执行至少一个计算。这可能会为查询添加数百,数千或数百万计算,以便我们可以与单一条件(例如 2014-02-07 进行比较)。改变标准以适应数据效率要高得多。

修改适合数据的条件是我使用 SARGABLE 谓词






不要在两者之间使用。


日期和时间范围的***做法是避免BETWEEN和
总是使用以下格式:



WHERE col> ='20120101'AND col 类型和所有精度,无论时间部分是否为
适用。


http://sqlmag.com/t-sql/ t-sql-best-practices-part-2 (Itzik Ben-Gan)


Select * from [User] U
where  U.DateCreated = '2014-02-07'     

but in the database the user was created on 2014-02-07 12:30:47.220 and when I only put '2014-02-07'

It does not show any data

DON'T be tempted to do things like this:

Select * from [User] U where convert(varchar(10),U.DateCreated, 120) = '2014-02-07'

This is a better way:

Select * from [User] U 
where U.DateCreated >= '2014-02-07' and U.DateCreated < dateadd(day,1,'2014-02-07')

see: Sargable

EDIT + There are 2 fundamental reasons for avoiding use of functions on data in the where clause (or in join conditions).

  1. In most cases using a function on data to filter or join removes the ability of the optimizer to access an index on that field, hence making the query slower (or more "costly")
  2. The other is, for every row of data involved there is at least one calculation being performed. That could be adding hundreds, thousands or many millions of calculations to the query so that we can compare to a single criteria like 2014-02-07. It is far more efficient to alter the criteria to suit the data instead.

"Amending the criteria to suit the data" is my way of describing "use SARGABLE predicates"


And do not use between either.

the best practice with date and time ranges is to avoid BETWEEN and to always use the form:

WHERE col >= '20120101' AND col < '20120201' This form works with all types and all precisions, regardless of whether the time part is applicable.

http://sqlmag.com/t-sql/t-sql-best-practices-part-2 (Itzik Ben-Gan)