如何查询DateTimeOffset列以获取特定日期的所有行?

时间:2019-01-16 14:12:50

标签: tsql

因此,假设您有一个表格,其下面的列(类型为datetimeoffset(3))。

    DTO_Created
    2017-04-28 03:16:56.942 -05:00
    2017-05-01 00:20:54.925 -05:00
    2017-05-01 12:17:52.752 -05:00
    2017-05-01 23:21:00.198 -05:00
    2017-05-02 01:19:23.254 -05:00

您将如何查询以仅获取在2017-05-01创建的行? (共3行)我正在尝试执行此操作,但未获得全部3行。

SELECT * FROM MyTable WHERE DTO_Created >= '2017-05-01 00:00:00.000' AND DTO_Created <= '2017-05-01 23:59:59.999'

问题似乎是由类型(datetimeoffset)引起的,因为常规的datetime列不会发生这种情况。


环境:SQL Server 2016

2 个答案:

答案 0 :(得分:1)

您还需要对datetimeoffset子句使用where

首先,创建并填充示例表(在您将来的问题中为我们保存此步骤):

DECLARE @T AS TABLE
(
    DTO_Created DateTimeOffset
)

INSERT INTO @T(DTO_Created) VALUES
('2017-04-28 03:16:56.942 -05:00'),
('2017-05-01 00:20:54.925 -05:00'),
('2017-05-01 12:17:52.752 -05:00'),
('2017-05-01 23:21:00.198 -05:00'),
('2017-05-02 01:19:23.254 -05:00')

查询:

SELECT *
FROM @T 
WHERE DTO_Created >= '2017-05-01 00:00:00.000 -05:00'
AND DTO_Created < '2017-05-02 00:00:00.000 -05:00'

结果:

DTO_Created
2017-05-01 00:20:54.925 -05:00
2017-05-01 12:17:52.752 -05:00
2017-05-01 23:21:00.198 -05:00

2016年或更高版本的另一种选择是使用AT TIME ZONE,但是您必须将时差添加到搜索值中,并提防夏时制:

SELECT *
FROM @T 
WHERE DTO_Created >= CAST('2017-05-01 05:00:00' AS DateTime2) AT TIME ZONE 'Easter Island Standard Time' -- -05:00
AND  DTO_Created < CAST('2017-05-02 05:00:00' AS DateTime2) AT TIME ZONE 'Easter Island Standard Time' 

如果您想忽略当地时间,将DateTimeOffset的UTC部分视为DateTime,则可以将DateTimeOffset强制转换为Date,尽管那样将是非sargable谓词:

SELECT *
FROM @T
WHERE CAST(DTO_Created As Date) = '2017-05-01'

答案 1 :(得分:1)

尝试一下

CONVERT(DATETIME, DTO_Created, 1) >= '2017-05-01 00:00:00.000' AND CONVERT(DATETIME, DTO_Created, 1) <= '2017-05-01 23:59:59.999'

或此

cast(DTO_Created as datetime) >= '2017-05-01 00:00:00.000' AND cast(DTO_Created as datetime) <= '2017-05-01 23:59:59.999'