当转换 a 时DATETIMEOFFSET
,DATETIME
它将日期和时间作为值中的偏移量,并简单地删除时区。DATE
转换为or时也是如此TIME
。因此,我认为您可以简单地将列转换为DATE
并将其与您希望匹配的仅日期值进行比较:
DECLARE @targetDate DATETIME2 = '2012-09-04' --Or we could use DATE here
SELECT [PurchaseId], [PurchaseTime], CAST([PurchaseTime] AS DATE) AS "PurchaseDate"
FROM [Purchases]
WHERE CAST([PurchaseTime] AS DATE) = @targetDate
我不确定这会有多有效(如果提供者真的很聪明,希望不会很糟糕——SQL Server 可能会这样),但您也可以通过限制原始列值来改进它:
DECLARE @targetDate DATETIME2 = '2012-09-04' --DATETIME2 so we can adjust by hours
SELECT [PurchaseId], [PurchaseTime], CAST([PurchaseTime] AS DATE) AS "PurchaseDate"
FROM [Purchases]
WHERE CAST([PurchaseTime] AS DATE) = @targetDate --Keep only the local-date matches
AND [PurchaseTime] >= DATEADD(hh, -14, @targetDate) --Up to 14-hour time zone offset
AND [PurchaseTime] <= DATEADD(hh, 38, @targetDate) --24 hours later plus 14
这应该有效地索引到一组可能性,然后在转换为本地日期时正确过滤。请注意,时区偏移最长可达 14 小时(我知道新西兰最远的时间是 +13:00,但根据MSDN ,它们可以达到 +/- 14:00 ),@targetDate 将在天,因此它与 14 小时前和 24+14=38 小时后进行比较。DATETIME2 与 DATETIMEOFFSET 具有相同的范围和精度,因此它比原始 DATETIME 更好(但它也可以与 DATETIME 一起使用)。