首页 > 解决方案 > SQL Server 时区在 where 子句中

问题描述

我正在使用 UTC 时间存储日期时间字段。我们需要使用 CST 时区过滤记录。我试过这个查询:

select id, CreatedOn,
       CreatedOn AT TIME ZONE 'UTC' AT TIME ZONE 'Central Standard Time' AS LocalTime
from Status
WHERE CAST((CreatedOn AT TIME ZONE 'Central Standard Time') AS date) = '2018-09-06'
order by CreatedOn desc;

问题在于,当 UTC 时间更改为 9 月 6 日时,它还带来了在 CST 时间 9 月 5 日晚上保存的那些记录。在 CST 时间仅过滤掉 9 月 6 日记录的正确方法是什么?

标签: sqlsql-server

解决方案


我发现查询存在问题,我在 where 子句中缺少 'UTC' AT TIME ZONE。这是有效的正确查询:

select id, CreatedOn,
       CreatedOn AT TIME ZONE 'UTC' AT TIME ZONE 'Central Standard Time' AS LocalTime from CosmoStatus WHERE CAST((CreatedOn AT TIME ZONE
'UTC' AT TIME ZONE 'Central Standard Time') AS date) = '2018-09-06'
order by CreatedOn desc;

推荐阅读