【问题标题】:Not able to fetch records by Date from database无法从数据库中按日期获取记录
【发布时间】:2016-09-08 02:40:41
【问题描述】:

我有基于列 id 和日期的数据...日期的数据类型是 DATETIME

数据库:sql server 2008

查询一:

Select * 
from table t1 
where (t1.date between '2016-05-11' and  '2016-05-13')

查询2:

select * 
from table t1 
where t1.date IN ('2016-05-11')

结果是 NUll 即使我在这个日期有记录

那么有没有其他方法可以获取记录除了//>/>=) 大于或小于

【问题讨论】:

  • 请使用 Select * from table t1 where (t1.date between '2016-05-11' and '2016-05-13')
  • @ChetanSanghani 您的查询与查询 1 相同,我没有得到任何记录
  • 您的查询中缺少一个单引号

标签: sql-server database


【解决方案1】:

您可以使用以下查询,但您的查询也是正确的,并且它在我的服务器上运行。

Select * from table t1 
where t1.date between '20160511 00:00:00' and '20160513 23:59:59';

select * from table t1 where cast(t1.date as date) IN ('20160511');

【讨论】:

  • 如果我在数据库中有数据类型“日期”,它可以工作....但不能使用数据类型“日期时间”
  • 您使用的是哪个服务器版本?
  • sql server 2008 R2
  • 在 SQL server 2008 R2 上,我已经测试并运行了。
【解决方案2】:

试试这个,

Select * 
from table t1 
where cast(t1.date as date) between '2016-05-11' and  '2016-05-13'

ie 将您的日期时间列转换为日期并进行比较,因为您的参数只是日期值。 或

where cast(t1.date as date) in ('2016-05-11')--For your second query

或使用大于或小于

Select * 
from table t1 
where t1.date >= '2016-05-11' and  t1.date < '2016-05-14'

【讨论】:

  • @TomTom:这个答案怎么样??
  • @Abdul Rasheed,如果我在数据库中有数据类型“日期”,则转换查询正在工作......但不能使用数据类型“日期时间”。
  • 如果您没有得到查询结果 - where cast(t1.date as date) between '2016-05-11' 和 '2016-05-13' ,那么应该没有记录在此期间。
  • 查看图片...有问题...在“2016-05-11”和“2016-05-13”之间有 3 条记录可用...查询运行成功,但数据获取结果为 Null
  • 然后 chk - t1.date >= '2016-05-11' 和 t1.date
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-24
  • 1970-01-01
  • 2011-01-04
  • 1970-01-01
  • 2019-06-30
  • 2011-05-29
相关资源
最近更新 更多