在where子句中使用case语句创建查询

时间:2012-09-11 13:48:49

标签: sql tsql

我有一个大型存储过程来为报告提取数据。我试图根据某些条件在WHERE子句中使用两个不同值中的一个。我无法弄清楚如何使用CASE语句来完成此操作,我一直在THEN部分遇到错误。下面是我要做的,它是较大存储过程的一小部分。所以我要找的是dlp(DATETIME)dlc(DATETIME)更新我希望使用dlp来评估@AgeStart@AgeEnd参数,如果不是那么使用dlc@AgeStart@AgeEnd进行评估。

@AgeStart INT
@AgeEnd INT

SET @Recovery = (
SELECT SUM(ISNULL(M.Paid1, 0))
FROM Master AS M
WHERE M.Status IN ('xxx','yyy')
  AND CASE
    WHEN COALESCE(M.dlp, '2000-01-01 00:00:00') > 
         COALESCE(M.dlc, '2000-01-01 00:00:00') 
    THEN DATEDIFF(dd,M.Received,M.dlp) 
      >= @AgeStart AND DATEDIFF(dd,M.Received,M.dlp) <= @AgeEnd
    ELSE DATEDIFF(dd, M.dlc, M.Received) 
      >= @AgeStart AND DATEDIFF(dd, M.dlc, M.Received) <= @AgeEnd
  END
  AND M.Balance >= @OrigBalanceMin AND M.Balance <= @OrigBalanceMax
)

1 个答案:

答案 0 :(得分:1)

您不需要案例陈述,您可以将它们嵌套在括号中并使用OR条件。我我排好了所有的括号:

WHERE M.Status IN ('xxx','yyy')
    AND 
    /* Your updated case statement starts here */
    (
        (
            COALESCE(M.dlp, '2000-01-01 00:00:00') > 
                COALESCE(M.dlc, '2000-01-01 00:00:00') AND 
            DATEDIFF(dd,M.Received,M.dlp) >= @AgeStart AND 
                DATEDIFF(dd,M.Received,M.dlp) <= @AgeEnd
        ) OR (
            COALESCE(M.dlp, '2000-01-01 00:00:00') <= 
                COALESCE(M.dlc, '2000-01-01 00:00:00') AND 
            DATEDIFF(dd, M.dlc, M.Received) >= @AgeStart AND 
                DATEDIFF(dd, M.dlc, M.Received) <= @AgeEnd
        )
    )
    /* Your updated case statement ends here */
    AND M.Balance >= @OrigBalanceMin AND M.Balance <= @OrigBalanceMax
)