SQL Server - 在WHERE子句中使用CASE

时间:2011-09-30 04:40:39

标签: sql sql-server sql-server-2008

我想在CASE子句中使用WHERE,但它会返回错误。

我可以在where子句中使用CASE吗?或者如何修复它?感谢

SELECT * FROM hris_leave.dbo.tbl_act 
inner join hris_leave.dbo.tstaff on hris_leave.dbo.tstaff.s_id =        hris_leave.dbo.tbl_act.s_id 
where 
 case when acting_to is not null 
then 
datediff(day, acting_from, acting_to) >= 90 and acting_to >= '2010-10-01' 
else
acting_to is null
order by  hris_leave.dbo.tbl_act.s_id 

1 个答案:

答案 0 :(得分:7)

在您的情况下,您只需要OR

WHERE
    (
    acting_to is null 
    OR 
        (
        datediff(day, acting_from, acting_to) >= 90
        AND
        acting_to >= '2010-10-01'
        )
    )

案例是,而不是条件。条件超出了CASE表达式

例如

CASE
    WHEN SomeCol = 'a' THEN ColA
    WHEN SomeCol = 'c' THEN ColC
    ELSE ColB
END > 42