我在WHERE子句中遇到CASE语句问题。在我的查询中,我想获得日期之前的行。日期检查3列。 date1
不是NULL,所以我不需要进行NULL检查,但是日期date2
和date3
可以为NULL,所以我想检查空值并相应地检查日期条件。我尝试了两种方法,但无法弄清楚如何正确地做到这一点。你能帮我吗?
查询1:
SELECT *
FROM
docs
WHERE
date1 < '20120601'
AND CASE
WHEN date2 IS NOT NULL AND date3 IS NOT NULL THEN date2 < '20120601'
WHEN date2 IS NOT NULL AND date3 IS NULL THEN date2 < '20120601'
WHEN date2 IS NULL AND date3 IS NOT NULL THEN date3 < '20120601'
END
第一次出现时出现错误:Incorrect syntax near '<'.
我将查询修改为:
SELECT *
FROM
docs
WHERE
date1 < '20120601'
AND CASE
WHEN date2 IS NOT NULL AND date3 IS NOT NULL AND date2 < '20120601' THEN TRUE
WHEN date2 IS NOT NULL AND date3 IS NULL AND date2 < '20120601' THEN TRUE
WHEN date2 IS NULL AND date3 IS NOT NULL AND date3 < '20120601' THEN TRUE
END
又出现了另一个错误:An expression of non-boolean type specified in a context where a condition is expected, near 'END'.
答案 0 :(得分:7)
这应该有效:
SELECT *
FROM
docs
WHERE (date1 < '20120601')
OR (date2 IS NOT NULL AND date2 < '201205601')
OR (date2 IS NULL AND date3 IS NOT NULL AND date3 < '20120601')
答案 1 :(得分:2)
where
date1 < '20120601'
and
coalesce(date2, date3, '20000101') < '20120601'
答案 2 :(得分:0)
这个怎么样?
SELECT *
FROM
docs
WHERE date1 < '20120601'
AND ISNULL(date2, '20120601') < '20120601'
AND ISNULL(date3, '20120601') < '20120601'
答案 3 :(得分:0)
正确的答案是:
SELECT *
FROM
docs
WHERE
date1 < '20120601' AND
((date2 IS NOT NULL AND date3 IS NOT NULL AND date2 < '20120601') OR
(date2 IS NOT NULL AND date3 IS NULL AND date2 < '20120601') OR
(date2 IS NULL AND date3 IS NOT NULL AND date3 < '20120601'))