2

我对 WHERE 子句中的 CASE 语句有疑问。在我的查询中,我想获取日期之前的行。日期在 3 列上进行检查。date1is NOT NULL 所以我不需要有一个 NULL 检查,但是日期date2并且date3可以是 NULL 所以我想检查空值并相应地检查日期条件。我尝试了两种方法,但无法弄清楚如何正确地做到这一点。你能帮我吗?

查询一:

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'.

4

4 回答 4

8

这应该有效:

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')
于 2012-11-10T12:20:55.950 回答
2
where
date1 < '20120601'
    and
coalesce(date2, date3, '20000101') < '20120601'
于 2012-11-10T12:57:49.507 回答
0

那这个呢 ?

SELECT *
FROM
    docs
WHERE date1 < '20120601'
  AND ISNULL(date2, '20120601') < '20120601'
  AND ISNULL(date3, '20120601') < '20120601'
于 2012-11-10T12:17:01.330 回答
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'))
于 2013-12-19T20:02:14.133 回答