patternsqlCritical
Case with multiple conditions
Viewed 0 times
casewithmultipleconditions
Problem
I need to change returned value, from select statement, based on several conditions. I tried something like that:
why it is not working and what is recommended way to do this ?
There will be next several WHEN conditions.
Thank you
,CASE i.DocValue
WHEN 'F2' AND c.CondCode IN ('ZPR0','ZT10','Z305') THEN c.CondVal
ELSE 0
END as Valuewhy it is not working and what is recommended way to do this ?
There will be next several WHEN conditions.
Thank you
Solution
,CASE WHEN i.DocValue ='F2' AND c.CondCode IN ('ZPR0','ZT10','Z305') THEN c.CondVal
ELSE 0
END as ValueThere are two types of
CASE statement, SIMPLE and SEARCHED.You cannot evaluate multiple expressions in a Simple case expression, which is what you were attempting to do.
-- 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 ]
ENDExample of Simple CASE:
CASE x
WHEN 'a' THEN 'b'
WHEN 'c' THEN 'd'
ELSE 'z'
ENDExample of a Searched CASE:
CASE
WHEN x = 1 AND y = 2 THEN 'a'
WHEN x = 2 AND y = 1 THEN 'b'
ELSE 'z'
ENDFurther Reading: http://msdn.microsoft.com/en-us/library/ms181765.aspx
Code Snippets
,CASE WHEN i.DocValue ='F2' AND c.CondCode IN ('ZPR0','ZT10','Z305') THEN c.CondVal
ELSE 0
END as Value-- 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 ]
ENDCASE x
WHEN 'a' THEN 'b'
WHEN 'c' THEN 'd'
ELSE 'z'
ENDCASE
WHEN x = 1 AND y = 2 THEN 'a'
WHEN x = 2 AND y = 1 THEN 'b'
ELSE 'z'
ENDContext
StackExchange Database Administrators Q#82487, answer score: 53
Revisions (0)
No revisions yet.