具有多个条件的SQL Server CASE

时间:2017-06-15 13:23:23

标签: sql-server-2012

我正在尝试弄清楚如何使用多个条件执行SQL Server CASE命令。

我正在尝试使用条件

If column_a = 'test' AND column_b IS NULL OR (column_b IS NOT NULL AND Column_c = Column_d) OR Column_e >= 480 THEN 'OK'
ELSE 'CHECK'
END

所以我想说的是:

If column_a = 'test' AND column_b IS NULL return 'OK'
OR If column_a = 'test' AND (column_b IS NOT NULL AND Column_c = Column_d) OR Column_e >= 480 THEN 'OK'

所以我为声明写的是

CASE WHEN column_a = 'test' AND column_b IS NULL OR (column_b IS NOT NULL AND Column_c = Column_d) OR Column_e >= 480 THEN 'OK'
ELSE 'CHECK'
END

我没有得到任何错误,只是没有得到理想的结果。这是SQL Server中多个AND OR语句的正确顺序吗?

2 个答案:

答案 0 :(得分:2)

我会把它分解一下。我会建议这样的事情:

CASE 
    WHEN column_a='test' AND column_b IS NULL
    THEN 'OK'
    WHEN column_a = 'test' AND (column_b IS NOT NULL AND Column_c = Column_d) OR Column_e >= 480
    THEN 'OK'
    ELSE 'CHECK'
END

答案 1 :(得分:1)

试试这个:

case 
    when column_a = 'test'
    and (column_b is null 
        or
        (column_b is not null and column_c = column_d))
        or column_e >=480
        then 'OK'

或显示一些样本数据和预期结果,以便我们更好地了解它的作用