首页 > 解决方案 > SQL Server:日期不一致

问题描述

create table #temp
(
  A date
)

insert into #temp(A)
values(GETDATE())
insert into #temp(A)
values(GETDATE()-1)

现在,当我将表查询为

select A from #temp where A>=GETDATE() and A<=GETDATE()

我没有得到任何记录但是GETDATE()记录值应该满足我的 where 条件,它不应该至少传递给我一个记录吗?

如果我在这里遗漏了一些要点,请指导我。

标签: sqlsql-server

解决方案


您需要进行转换,所以看起来:

where a >= convert(date, dateadd(day, -1, getdate())) and 
      a <= convert(date, getdate());

您的where条款比较日期为:

where a >= '2020-04-21 16:01:27.277' and a <= '2020-04-21 16:01:27.277'

因此,您需要转换日期,因为getdate()还会返回时间部分。

由于您的where子句查找单日,因此您可以这样做:

where a = convert(date, getdate())

推荐阅读