tags:

views:

14

answers:

1

I am trying to do a select which would return a blank '' when a join is not successfull

(when a blank '' or a '-' is encountered in column)

and return column value when it is successfull. I am using case for this but not succeeding until now. Anyone can advise a better query ?

select a.EmpName,a.deptcode,(a.deptcode||' '||(SELECT CASE(a.deptcode) WHEN a.deptcode='-' THEN '' ELSE b.deptname)) as FULLDEPTNAME from table1 a LEFT OUTER JOIN tableB b on a.deptcode=b.deptcode WHERE a.empNo=12;
+1  A: 

(when a blank '' or a '-' is encountered in column)

If a join is unsuccessful, the column value will be null (not blank or hyphen).

Maybe this works better

  a.deptcode || '  ' || coalesce (b.deptname, '<missing>') as fulldeptname
Thilo
Thanks, is using COALESCE preferred over CASE for comparing nulls ? If yes, does it give any performance advantage ?
Popo
CASE WHEN b.deptname IS NULL should work, too. Not sure about performance impact (if anything COALESCE should be faster, because it is "simpler" and less general) , but COALESCE is shorter to type (if you can remember how to spell it) and easier to read.
Thilo
Popo
for more complex cases, you can use CASE/WHEN. Why do you need to check for "-" ?
Thilo
Some rows have '-' also. I am still looking to return alternate values with COALESCE(in case of '' COlumnA else ColumnB).
Popo
COALESCE can only check for null. In Oracle, you'd have DECODE as well, but in DB2 I guess you are stuck with CASE (which should work, though, so no problem, right).
Thilo
Yep I have got CASE working fine.
Popo