3

我有一个为报告提取数据的大型存储过程。我试图WHERE根据某些标准在子句中使用两个不同的值之一。我不知道如何使用CASE语句来完成这项工作,我不断收到THEN部分错误。以下是我正在尝试做的事情,它是较大存储过程的一小部分。所以我正在寻找的是dlp(DATETIME)dlc(DATETIME)我想用and参数dlp评估的地方更新,如果没有,那么用and评估。@AgeStart@AgeEnddlc@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
)
4

1 回答 1

1

您不需要 case 语句,您可以将它们嵌套在括号中并使用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
)
于 2012-09-11T13:54:01.860 回答