案例没有正确评估sql server

时间:2014-02-11 13:25:58

标签: sql sql-server tsql case-when

我在提取查询中的语句中有一个大小写,它似乎没有返回我期待的内容

DECLARE @Val1 int, @Val2 int,@Val3 int, @Val4 int, @Val5 int

SELECT  @Val1 = 5 , @Val2= 2,@Val3= 200000, @Val5  = 2,@Val4 = 2014
SELECT  @Val1 , @Val2,@Val3, @Val4, @Val5   

SELECT CASE

        WHEN  @Val1 = 5 AND @Val2  IN(1,2) AND @Val3 = 200000 AND @Val4 IS NULL  THEN 'ReturnValue1'
        WHEN  @Val1 = 5 AND @Val2  IN(1,2) AND @Val3 = 200000 AND @Val4 IS NOT NULL THEN 'ReturnValue2'
        WHEN  @Val1 = 5 AND @Val2  = 2 AND @Val3 = 200000  AND @Val5 = 2 AND @Val4 IS NOT NULL THEN 'ReturnValue3'
        ELSE NULL
    END [TestingValue]

我期望该值为 ReturnValue3 但是由于某种原因它似乎忽略了整行。

任何人都可以看到我没有发现的问题。

2 个答案:

答案 0 :(得分:4)

对于大多数情况

  

CASE语句按顺序评估其条件并停止   满足条件满足的第一个条件

http://msdn.microsoft.com/en-us/library/ms181765.aspx

答案 1 :(得分:1)

ReturnValue3是ReturnValue2的子集,因此您需要先检查ReturnValue3,否则所有满足ReturnValue3的组合都将被分配给ReturnValue2。

DECLARE @Val1 int, @Val2 int,@Val3 int, @Val4 int, @Val5 int

SELECT  @Val1 = 5 , @Val2= 2,@Val3= 200000, @Val5  = 2,@Val4 = 2014
SELECT  @Val1 , @Val2,@Val3, @Val4, @Val5   

SELECT CASE
        WHEN  @Val1 = 5 AND @Val2  IN(1,2) AND @Val3 = 200000 AND @Val4 IS NULL  
         THEN 'ReturnValue1'
        WHEN  @Val1 = 5 AND @Val2  = 2 AND @Val3 = 200000  AND @Val5 = 2 AND @Val4 IS NOT NULL 
         THEN 'ReturnValue3'
        WHEN  @Val1 = 5 AND @Val2  IN(1,2) AND @Val3 = 200000 AND @Val4 IS NOT NULL 
         THEN 'ReturnValue2'
        ELSE NULL
    END [TestingValue]