【问题标题】:SQL Server - CASE WHEN in WHERE clause with DATEDIFF functionSQL Server - 带有 DATEDIFF 函数的 WHERE 子句中的 CASE WHEN
【发布时间】:2018-05-02 03:38:33
【问题描述】:

我正在尝试使用 case when 和 DATEDIFF 函数执行以下 where 语句。但我收到语法错误。请帮帮我。

WHERE
    -- primary contract is Flowing
    CTS.ContractStatusIdentifier = 'FLW'                                         
    AND (CASE 
            WHEN VMO.ProvinceOrStateCode = 'ON'
               THEN DATEDIFF (dd, CTR.RenewalDate, @currentdate) >= 75
               ELSE DATEDIFF (dd, CTR.RenewalDate, @currentdate) >= 45)
    AND VMO.ProvinceOrStateCode IN ('ON','AB')

【问题讨论】:

  • 两个问题:首先,CASE 需要由缺少的END 终止。其次,T-SQL 中的CASE 是一个返回单个原子值的表达式 - 您不能有选择地执行一个或另一个代码块,您需要返回 a值(如数字或字符串) - 不是代码块

标签: sql-server where-clause datediff case-when


【解决方案1】:

显然是WHERE 子句语法

AND (CASE 
        WHEN VMO.ProvinceOrStateCode = 'ON'
           THEN DATEDIFF (dd, CTR.RenewalDate, @currentdate) >= 75
           ELSE DATEDIFF (dd, CTR.RenewalDate, @currentdate) >= 45)

无效。简单来说很简单,请尝试

AND DATEDIFF (dd, CTR.RenewalDate, @currentdate)
    >= (CASE 
           WHEN VMO.ProvinceOrStateCode = 'ON'
               THEN 75
               ELSE 45
        END)

祝你好运

【讨论】:

    【解决方案2】:

    SELECT [supp_call_tckt_num], UPPER([assigned_to]) as assigned_to,

    assigned_date, close_date, diffday = CASE WHEN close_date is null then

    datediff(d,assigned_date,getdate()) 其他

    datediff(d,assigned_date,close_date) 结束,

    UPPER([call_source]) 作为 call_source,

    UPPER([account_type]) as account_type, [mdn],

    UPPER([status]) 作为状态,UPPER([company_name]) 作为公司名称,

    UPPER([rep_id]) as rep_id, UPPER([caller_first_name]) caller_first_name,

    UPPER([caller_last_name]) as caller_last_name, [account_number],

    UPPER([network]) 作为网络,UPPER([issue_type]) 作为 issue_type,

    UPPER([problem]) 作为问题,UPPER([subtype]) 作为子类型,UPPER([prob_desc_res])

    as prob_desc_res, UPPER([notes]) as notes, [ticket_number] FROM [ewts_tracker] with (NOLOCK) WHERE [ewts_tracker].[escalated] =

    “是”和 datediff (d,isnull(assigned_date,getdate()),close_date) >= '3'

    【讨论】:

      猜你喜欢
      • 2013-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多