且构网

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

如何在Microsoft SQL Server中仅使用日期查询DATETIME字段?

更新时间:2023-01-29 10:11:35

使用范围或DateDiff函数

use range, or DateDiff function

 select * from test 
 where date between '03/19/2014' and '03/19/2014 23:59:59'

 select * from test 
 where datediff(day, date, '03/19/2014') = 0

其他选项是:


  1. 如果您对数据库模式有控制权,而您没有不需要
    时间数据,将其取出。

  1. If you have control over the database schema, and you don't need the time data, take it out.

,或者,如果必须保留它,则添加具有时间部分的计算列属性日期值的剥离...

or, if you must keep it, add a computed column attribute that has the time portion of the date value stripped off...

更改表测试
添加DateOnly As
DateAdd(day,datediff(day,0,date),0)

或者,在最新版本的SQL Server ...

or, in more recent versions of SQL Server...

更改表测试
仅将DateAdd添加为
Cast(DateAdd(day,datediff(day, 0,date),0)as Date)

然后,您可以简单地编写查询:

then, you can write your query as simply:

select * from test 
where DateOnly = '03/19/2014'