有多种情况的情况


14

我需要根据几种条件从select语句更改返回值。我尝试过这样的事情:

,CASE i.DocValue
  WHEN 'F2' AND c.CondCode IN ('ZPR0','ZT10','Z305') THEN c.CondVal
  ELSE 0
END as Value

为什么它不起作用?推荐的方法是什么?接下来将有几个WHEN条件。

谢谢

Answers:


25
,CASE WHEN i.DocValue ='F2' AND c.CondCode IN ('ZPR0','ZT10','Z305') THEN c.CondVal
  ELSE 0
END as Value

CASE语句有两种类型,SIMPLESEARCHED

您不能在简单案例表达式中评估多个表达式,而这正是您试图做的。

-- Simple CASE expression: 
CASE input_expression 
     WHEN when_expression THEN result_expression [ ...n ] 
     [ ELSE else_result_expression ] 
END 
-- Searched CASE expression:
CASE
     WHEN Boolean_expression THEN result_expression [ ...n ] 
     [ ELSE else_result_expression ] 
END

简单案例的例子:

CASE x
  WHEN 'a' THEN 'b'
  WHEN 'c' THEN 'd'
  ELSE 'z'
END

搜索案例的示例:

CASE 
  WHEN x = 1 AND y = 2 THEN 'a'
  WHEN x = 2 AND y = 1 THEN 'b'
  ELSE 'z'
END

进一步的阅读:http : //msdn.microsoft.com/en-us/library/ms181765.aspx


1

如果您有多个要求,也可以这样写:

CASE WHEN CITY='HYDERABAD' THEN       
 CASE WHEN AREA='BHILL' THEN PIN='12345'      
 WHEN AREA='DSNR' THEN PIN='67890'          
 ELSE '33333'          
 END           
END AS PIN_COD

您是对的,复杂条件的嵌套案例也可以使用:)
Muflix
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.