在 SQL Server 2008 查询中使用 DateTimeOffset 作为 WHERE 条件

发布于 2024-09-28 09:51:00 字数 518 浏览 1 评论 0原文

我想知道是否有人可以帮助我理解为什么这两个标准不返回相同的结果集。对我来说,SQL Server 2008 R2 不知道在约束数据时使用偏移量似乎很奇怪。有更好的方法吗?据我所知,标准二是获得正确数据的唯一方法。

-- Criteria One
OriginationDateTimeOffset >= TODATETIMEOFFSET('2010-10-20', '-08:00') AND
OriginationDateTimeOffset < TODATETIMEOFFSET('2010-10-21', '-08:00')

-- Criteria Two
SWITCHOFFSET(OriginationDateTimeOffset, '-08:00') >= TODATETIMEOFFSET('2010-10-20', '-08:00') AND
SWITCHOFFSET(OriginationDateTimeOffset, '-08:00') < TODATETIMEOFFSET('2010-10-21', '-08:00')

I was wondering if anyone could help me understand why these two criteria do not return the same result sets. To me, it seems weird that SQL Server 2008 R2 wouldn't know to use the offset while constraining the data. Is there a better way to do this? As far as I can tell, Criteria Two is the only way to get the correct data.

-- Criteria One
OriginationDateTimeOffset >= TODATETIMEOFFSET('2010-10-20', '-08:00') AND
OriginationDateTimeOffset < TODATETIMEOFFSET('2010-10-21', '-08:00')

-- Criteria Two
SWITCHOFFSET(OriginationDateTimeOffset, '-08:00') >= TODATETIMEOFFSET('2010-10-20', '-08:00') AND
SWITCHOFFSET(OriginationDateTimeOffset, '-08:00') < TODATETIMEOFFSET('2010-10-21', '-08:00')

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

陌路黄昏 2024-10-05 09:51:00

为什么它会返回相同的结果?在标准 1 中,您将原始时间与偏移量进行比较,而在标准 2 中,您将更改两者的偏移量。

Why would it return the same? In criteria 1 you are comparing the original time to the offset, where in criteria 2 you are changing the offset on both.

怎言笑 2024-10-05 09:51:00

TODATETIMEOFFSET 将值转换为日期时间偏移。 SWITCHOFFSET 将值更改为另一个日期时间偏移量。例如:

DECLARE @OriginationDateTimeOffset DATETIMEOFFSET = '2010-10-20'

SELECT @OriginationDateTimeOffset, 
    SWITCHOFFSET(@OriginationDateTimeOffset, '-08:00'),
    TODATETIMEOFFSET(@OriginationDateTimeOffset, '-08:00')

产生:

2010-10-20 00:00:00.0000000 +00:00
2010-10-19 16:00:00.0000000 -08:00
2010-10-20 00:00:00.0000000 -08:00

TODATETIMEOFFSET converts the value(s) to datetimeoffset. SWITCHOFFSET changes the value to another datetimeoffset. For example:

DECLARE @OriginationDateTimeOffset DATETIMEOFFSET = '2010-10-20'

SELECT @OriginationDateTimeOffset, 
    SWITCHOFFSET(@OriginationDateTimeOffset, '-08:00'),
    TODATETIMEOFFSET(@OriginationDateTimeOffset, '-08:00')

produces:

2010-10-20 00:00:00.0000000 +00:00
2010-10-19 16:00:00.0000000 -08:00
2010-10-20 00:00:00.0000000 -08:00
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文