2017-06-15 59 views
0

我想弄清楚如何在多个条件下执行SQL Server CASE命令。具有多个条件的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语句的正确顺序吗?

感谢您的任何帮助,您可以提供

回答

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' 

或显示一些示例数据和预期的结果,所以我们可以得到一个更好地了解其做

+0

谢谢dbajr - 我试过了,它为我工作。非常感激。 – spittingfire

1

我会分解它有点不同。我建议是这样的:

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 
+0

感谢联发你的建议有用非常赞赏 – spittingfire