我要检查
SELECT
*
FROM
table
WHERE
CASE
WHEN startdate IS NULL
THEN updatedon >= enddate
ELSE updatedon BETWEEN startdate AND enddate
在条件“>”中THEN块中出现错误。
答案 0 :(得分:3)
您可以使用布尔逻辑代替case
表达式:
select *
from table t
where (startdate is null and updatedon >= enddate) or
(startdate is not null and (updatedon >= startdate and updatedon <= enddate)
);
答案 1 :(得分:1)
您不能因CASE而患病,请尝试以下操作:
SELECT *
FROM _table
WHERE startdate IS NULL
AND updatedon >= enddate
OR startdate IS NOT NULL
AND updatedon BETWEEN startdate AND enddate;
答案 2 :(得分:0)
类似于其他答案,这将产生预期的结果:
SELECT *
FROM table
WHERE (
(startdate IS NOT NULL AND updatedon BETWEEN startdate AND enddate)
OR (startdate IS NULL AND updatedon >= enddate)
);
但是,如果您仍然想使用CASE WHEN,那么它看起来可能像这样:
SELECT *
FROM table
WHERE
(CASE
WHEN startdate IS NOT NULL AND updatedon BETWEEN startdate AND enddate THEN 1
WHEN startdate IS NULL AND updatedon >= enddate THEN 2
ELSE 0
END) > 0
请注意,CASE WHEN返回一个值。
但是那只会使SQL过于复杂。可能表现不佳。
因为查询优化器很难找到最快的执行计划。
答案 3 :(得分:0)
在下面的代码中,如果startdate
不是NULL
,那么将使用updatedon BETWEEN startdate AND enddate
。否则-updatedon BETWEEN enddate AND '31-12-9999'
,其中'31-12-9999'
等于date
类型的最大值,因此,它等于updatedon >= enddate
。
SELECT *
FROM _table
WHERE updatedon BETWEEN ISNULL(startdate, enddate) AND CASE
WHEN startdate IS NULL
THEN DATEFROMPARTS(9999, 12, 31)
ELSE enddate
END;