views:

595

answers:

4

Just wondering if there is a better way to write the following PL/SQL piece of code in ORACLE ?

IF(p_c_courtesies_cd is not null 
OR  p_c_language_cd is not null
OR v_c_name is not null
OR v_c_firstname is not null
OR v_c_function is not null
OR p_c_phone is not null
OR p_c_mobile is not null
OR p_c_fax is not null
OR v_c_email is not null
) THEN
     -- Do something
END IF;
+5  A: 
If coalesce( expr1, expr2, ... expr_n ) is not null then do something end if;

See here.

(Thanks Tony for the correction)

Otávio Décio
You missed "is not null"
Tony Andrews
Not sure I agree this is better. It's shorter. The original really conveys the intent though.
Dave Costa
In the original you have to read every line, including the "OR"s and the "IS NOT NULL"s - if one of the lines said "IS NULL" by mistake it might be missed (although formatting would have helped there) - however the COALESCE function is cleaner and conveys the intent perfectly.
Jeffrey Kemp
+1  A: 

if coalesce(expr1,expr2,...exprn) is not null then ...

jmucchiello
A: 

Another way, exploiting the fact that Oracle treats NULL and '' as the same:

IF p_c_courtesies_cd 
   || p_c_language_cd 
   || v_c_name 
   || v_c_firstname 
   || v_c_function 
   || p_c_phone 
   || p_c_mobile p_c_fax 
   || v_c_email is not null
THEN
     -- Do something
END IF;
Tony Andrews
While this will work in Oracle, keep in mind that it is not compliant behavior with the SQL-92 standard. See http://stackoverflow.com/questions/462471/is-this-implementation-sql-92-conformant
DCookie
+1  A: 

My answer would be a simple "No".

Although there are several alternative ways of writing the same construct, I don't think any are necessarily "better".

Anyone can look at the IF statement and know exactly what it means. The alternatives based around concatenation or using the coalesce operator just obscure the intent.

Nick Pierpoint
+1 All the other methods (including mine) save TYPING, but at the expense of clarity of meaning. I wouldn't be surprised if the original statement didn't perform best as well.
Tony Andrews
Nick, I'd say the person who couldn't read COALESCE and won't do some RTFM is in the wrong business.
Stew S
Perhaps, but it doesn't add anything apart from reduced clarity.
Nick Pierpoint