我有一个大型存储过程来为报告提取数据。我试图根据某些条件在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
)
答案 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
)