【问题标题】:How to Write Case Statement Using sys.time_zone_info如何使用 sys.time_zone_info 编写案例语句
【发布时间】:2023-01-26 22:50:35
【问题描述】:

在编写 Case 语句以从 SQL Server 中的 sys.time_zone_info 系统视图获取“美国东部标准时间”方面需要帮助。 Select 语句中有错误,无法确定错误位置。 CN.CreateDate 当前采用 UTC 时间,需要转换为 EST 以考虑夏令时。

select 
CN.CreateDate
,case when (SELECT * FROM sys.time_zone_info TZI WHERE    
TZI.name = 'US Eastern Standard Time'
        AND ISNULL(TZI.is_currently_dst,0)=0) 
        THEN DATEADD(hour, -5,CN.CreateDate) 
        ELSE DATEADD(hour, -4,CN.CreateDate) 
        END AS CreateDateEST
from MC_CDCPContactNotes CN

【问题讨论】:

  • 您的WHEN 中没有布尔表达式,只有一个子查询。应该是WHEN {Sub Query} = '<Literal Value>'吗? WHEN {Sub Query} IS NULL?还有别的吗?
  • 你的案例表达只有一半。如果您更好地格式化子查询,它会变得更加明显。

标签: sql sql-server


【解决方案1】:

只是为了解决您的查询:

select 
  CN.CreateDate
  ,case when (SELECT 
                 count(*) 
                 FROM sys.time_zone_info TZI 
                 WHERE TZI.name = 'US Eastern Standard Time'
                 AND ISNULL(TZI.is_currently_dst,0)=0) = 1 
    THEN DATEADD(hour, -5,CN.CreateDate) 
    ELSE DATEADD(hour, -4,CN.CreateDate) 
    END AS CreateDateEST
 from MC_CDCPContactNotes CN

但我会像这样重写它:

select 
  CN.CreateDate
  ,dateadd(hour,-5+ISNULL(TZI.is_currently_dst,0),CN.CreateDate) as CreateDateEst 
from MC_CDCPContactNotes CN
join sys.time_zone_info TZI 
    on TZI.name = 'US Eastern Standard Time'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-17
    • 1970-01-01
    • 2019-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-28
    相关资源
    最近更新 更多