热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

TSQL选择以前日期的记录-TSQLSELECTpreviousdate'srecords

IwanttoselectallrecordsfromatableLogwheretheDateAndTimefieldvalues(oftypedatetime)

I want to select all records from a table Log where the DateAndTime field values (of type datetime) are for the day before today, whatever day it is.

我想从一个表日志中选择所有的记录,其中DateAndTime字段值(类型为datetime)用于前天,无论它是哪一天。

So if today is 2011-06-08, I want to select all rows where DateAndTime is greater than or equal to 2011-06-07 00:00:00 and also less than 2011-06-08 00:00:00.

如果今天是2011-06-08,我想选择日期和时间大于或等于2011-06-07 00:00并且小于2011-06-08 00:00的所有行。

I'm guessing the potential pitfall here would be it's behaviour on the 1st day of the month, as obviously a date like 2011-06-00 is invalid, and should be 2011-05-31.

我猜这里潜在的陷阱可能是在一个月的第一天,因为像2011-06-00这样的日期显然是无效的,应该是2011-05-31。

5 个解决方案

#1


23  

For SQL Server 2008 you can use this.

对于SQL Server 2008,您可以使用它。

select *
from [log]
where cast(DateAndTime as date) = cast(getdate()-1 as date)

Pre 2008 you can use this

在2008年之前,你可以使用这个

select *
from [log]
where DateAndTime >= dateadd(d, datediff(d, 0, getdate())-1, 0) and
      DateAndTime 

Related on DBA: Cast to date is sargable but is it a good idea?

与DBA相关:到目前为止的角色分配是有限制的,但这是一个好主意吗?

#2


3  

SELECT * FROM Log
WHERE DateAndTime >= DATEADD(DAY,-1, CAST(GETDATE() AS DATE))
AND DateAndTime 

#3


1  

This example assumes SQL Server:

本例假设SQL Server:

select *
from log
where convert(varchar(8), DateAndTime , 112)  = convert(varchar(8), getdate()-1, 112)

Essentially, convert the date to yyyymmdd (the 112 parameter) and then check it is equal to yesterday's date (getdate()-1), also converted to yyyymmdd.

本质上,将日期转换为yyyyymmdd(112个参数),然后检查它是否等于昨天的日期(getdate()-1),也转换为yyyyyyymmdd。

#4


0  

Assuming SQL Server

如果SQL Server

 declare @today date
 set @today = GETDATE()

 select * from Log where DateAndTime between DATEADD(dd, -1, @today ) and @today

#5


0  

It should include conditional operator and not between . Otherwise it includes today's records as well.

它应该包含条件运算符,而不是中间的。除此之外,它还包括今天的记录。

Declare @today date
Set @today = GETDATE()


Select YourcolumnNames from log
Where DateAndTime >= DATEADD(dd, -1, @today ) and DateAndTime 

Moreover, you should mention the column name and * should be avoided in the select statement. This can improve the performance

此外,您应该在select语句中提到列名和*。这可以提高性能


推荐阅读
author-avatar
宋十七
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有