Link to home
Start Free TrialLog in
Avatar of pvsbandi
pvsbandiFlag for United States of America

asked on

How to work with this Case Statement

Hi,

 I'm on DB2 UDB 9.7. Probably, this is a very easy one, but i can't seem to work this out.
 I have the following Case Statement.
 
(Case WHEN VAR1 = 'Y' THEN 'TEXT1' ELSE '' END) ||','||
(CASE WHEN VAR2 = 'Y' THEN 'TEXT2' ELSE '' END) ||','||
(CASE WHEN VAR3 = 'Y' THEN 'TEXT3' ELSE '' END) ||','||
(CASE WHEN VAR4 = 'Y' THEN 'TEXT4' ELSE '' END) ||','||
(CASE WHEN VAR5 = 'Y' THEN 'TEXT5' ELSE '' END)

Expected Result : TEXT1,TEXT2,TEXT3,TEXT4,TEXT5

For example, if only TEXT3 is there, then
Expected Result : Text3

When i do the above logic, i'm getting
,,,TEXT3,,

I don't want to show the commas if the value is not there. How to display that?

Please help.
Avatar of Kent Olsen
Kent Olsen
Flag of United States of America image

Hi Pvsbandi,

There are several ways around this, all equally "yuck".  One is to include the comma every time that you append a string.  That does leave you with a possible leading or trailing comma, but at least you don't get what you're seeing.  You can always filter the string to remove any leading comma.


You can also write a UDF to merge the strings, or use recursive SQL, but that does seem like overkill.


Kent
SOLUTION
Avatar of Member_2_276102
Member_2_276102

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Member_2_276102
Member_2_276102

Wouldn't {TRIM( BOTH...} be desirable? I'm not sure of the syntax for that version of DB2. There can be leading and trailing commas. Since commas are not inserted for non-'Y' values, I'm not sure how embedded commas could be duplicated.

Tom
Never mind that last comment about embedded commas. I was looking at Kent's example rather than the original. Kent's example apparently eliminates internal duplicates.

And I should have just edited that out of the comment, but I forgot that editing was available.

Tom
Avatar of pvsbandi

ASKER

Thank You both, so much!