如何使用SQL Server中的日期查询DATETIME字段? [英] How to query DATETIME field using only date in SQL Server?

查看:228
本文介绍了如何使用SQL Server中的日期查询DATETIME字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简单的问题,但我无法解决它...

Simple question but i can't manage to solve it yet...

我有一个表TEST与DATETIME字段,如下所示:

I have a table TEST with a DATETIME field, like this :

ID NAME DATE
1 TESTING 2014-03-19 20:05:20.000

我需要的是下面的查询返回此行和每行的日期= 03/19/2014,无论什么时候是:

What i need is the query below returns this row and every rows with date = 03/19/2014, no matter what time is :

select * from test where date = '03/19/2014';

但它不返回任何行。只有工作方式也指定时间:

But it returns no rows. Only way to work is specifying also the time :

select * from test where date = '03/19/2014 20:03:02.000';

提前感谢

推荐答案

使用范围或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...

更改表Test
添加日期作为
演员(DateAdd(date,datediff(日,0,日期),0)作为日期)

那么你可以简单地写你的查询:

then, you can write your query as simply:

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

这篇关于如何使用SQL Server中的日期查询DATETIME字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆