简体   繁体   English

仅在SQL Server的表中从前一天恢复数据

[英]Recover data only from the previous day in a table in SQL Server

I need to retrieve data from a table that has date referenced only the previous day, I am trying to do with the query below but I am not getting: 我需要从仅具有前一天引用日期的表中检索数据,我正在尝试使用下面的查询,但我没有得到:

SELECT 
    Log.ValorEntrada, Log.DataHoraEvento, Log.NumeroEntrada 
FROM 
    Log 
WHERE 
    Log.DataHoraEvento = (GETDATE()-1)

How can I get this result? 我怎样才能得到这个结果?

In SQL Server, GETDATE() has a time component. 在SQL Server中, GETDATE()有一个时间组件。 I would recommend: 我建议:

WHERE Log.DataHoraEvento >= CAST(GETDATE()-1 as DATE) AND
      Log.DataHoraEvento < CAST(GETDATE() as DATE)

This condition is "sargable", meaning that an index can be used. 这个条件是“sargable”,意味着可以使用索引。 The following also is: 以下还是:

WHERE CONVERT(DATE, Log.DataHoraEvento) >= CONVERT(DATE, GETDATE())

Almost all functions prevent the use of indexes, but conversion/casting to a date is an exception. 几乎所有函数都阻止使用索引,但转换/转换为日期是一个例外。

Finally, if you don't care about indexes, you can also write this as: 最后,如果您不关心索引,也可以将其写为:

WHERE DATEDIFF(day, Log.DataHoraEvento, GETDATE()) = 1

DATEDIFF() with day as the first argument counts the number of "day" boundaries between the two date/times. DATEDIFF()day作为第一个参数计算两个日期/时间之间的“日”边界数。 Everything that happened yesterday has exactly one date boundary. 昨天发生的一切都只有一个日期边界。

If DataHoraEvento is a DATETIME , its likely that it has the full time, hence GETDATE()-1 isn't getting any matches. 如果DataHoraEventoDATETIME ,则可能是它有全部时间,因此GETDATE()-1没有获得任何匹配。 You should search for a range like this: 你应该搜索这样的范围:

SELECT L.ValorEntrada, L.DataHoraEvento, L.NumeroEntrada 
FROM dbo.[Log] L
WHERE L.DataHoraEvento >= CONVERT(DATE,DATEADD(DAY,-1,GETDATE()))
AND L.DataHoraEvento < CONVERT(DATE,GETDATE());
SELECT Log.ValorEntrada, Log.DataHoraEvento, Log.NumeroEntrada 
FROM   Log 
WHERE  Log.DataHoraEvento >= DATEADD(dd,DATEDIFF(dd,1,GETDATE()),0) 
AND    Log.DataHoraEvento < DATEADD(dd,DATEDIFF(dd,0,GETDATE()),0)

You should also use SYSDATETIME() (if you on SQL Server 2008+) instead of GETDATE() as this gives you datetime2(7) precision. 您还应该使用SYSDATETIME() (如果您使用的是SQL Server 2008+)而不是GETDATE(),因为这会为您提供datetime2(7)精度。

你可以试试这个:

MEMBER BETWEEN DATEADD(day, -2, GETDATE()) AND DATEADD(day, -1, GETDATE())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM