| A question about using nested decode [message #630190] |
Mon, 22 December 2014 10:11  |
orausern
Messages: 826 Registered: December 2005
|
Senior Member |
|
|
Hi Experts,
I have a requiement that I am trying to solve by nested decode but it is giving wrong result for some values. I will be thankful for pointers on it. Following is the set up for a test case:
create table test(emp_id varchar2(20), name varchar2(20), email varchar2(100));
insert into test values ('1','a','a@b.com');
insert into test values ('2',null,'a1@b.com');
insert into test values ('3',null,null);
commit;
Teh requirement is to print name if it is not null. If it is null then print email. If email is also null then print emp_id.
Following is what I tried:
select decode(decode(name,null,nvl(email,'xxx')),'xxx',emp_id) from test where emp_id='3';
But this gives a null for emp_id of '2' and '1'. I am not sure where I am going wrong. Please suggest.
Thanks,
[EDITED by LF: fixed topic title typo]
[Updated on: Mon, 22 December 2014 17:00] by Moderator Report message to a moderator
|
|
|
|
| Re: A question aobut using nested decode [message #630193 is a reply to message #630190] |
Mon, 22 December 2014 11:02   |
cookiemonster
Messages: 13975 Registered: September 2008 Location: Rainy Manchester
|
Senior Member |
|
|
The outer decode says - if the inner decode is xxx then return emp_id.
It doesn't say to do anything else. So if the inner decode doesn't return xxx you get null.
Since you're on 11g, it would be a lot easier to use CASE.
|
|
|
|
|
|
| Re: A question aobut using nested decode [message #630195 is a reply to message #630194] |
Mon, 22 December 2014 11:26   |
orausern
Messages: 826 Registered: December 2005
|
Senior Member |
|
|
Thank you very much cookiemonster! I could get the resolution using CASE(DON'T know how to use nvl for the same purpose though!). Also got the suggestion to use the coalesce that works too very beautifully:
SELECT test.*,
CASE
WHEN name IS NOT NULL THEN name
WHEN name IS NULL AND email IS NOT NULL THEN email
ELSE emp_id
END
AS new_name
FROM test
--from OTN forum:
select test.*, coalesce(name,email, emp_id) from test
Thanks a million!
[Updated on: Mon, 22 December 2014 11:26] Report message to a moderator
|
|
|
|
|
|
|
|