Search code examples
sqloraclenull

Unable to UPDATE SQL table row when one of bind var value is NULL


I'm unable to update a table TABL_X1 when one of the bind variable value is null or blank.

F_NAME M_NAME L_NAME STATUS
---------------------------
FN1             LN1     NEW
FN2     MN2     LN2     NEW
FN3                     NEW

I use this statement to update dynamically from my input file value and map corresponding columns

UPDATE TABL_X1 
SET STATUS = 'INPROCESS' 
WHERE F_NAME = :NAME_FIR 
  AND MNAME = :NAME_MID 
  AND LNAME = :NAME_LAS 

The F_NAME, M_NAME, L_NAME may have values or may be null in some cases. So when I pass the bind var values to the query the table row don't update.

For e.g. the first row of table the below query don't update the row.

UPDATE TABL_X1 
SET STATUS = 'INPROCESS' 
WHERE F_NAME = 'FN1' 
  AND MNAME = :'' 
  AND LNAME = :'LN1' 

But if I skip the MNAME whose value is NULL originally in where condition and run the below, update happens fine.

 UPDATE TABL_X1 
 SET STATUS = 'INPROCESS' 
 WHERE F_NAME = 'FN1' 
   AND LNAME = :'LN1' 

Since my query is passed values dynamically from file input, how to handle and update the row even if one/more bind var values are NULL.


Solution

  • NULL (an unknown value) is never equal (or not equal) to anything else, including another NULL. If you want to compare potential NULL values then you need to use IS NULL to check whether they ar each individually NULL:

    UPDATE TABL_X1 
    SET STATUS = 'INPROCESS' 
    WHERE (F_NAME = :NAME_FIR OR (F_NAME IS NULL AND :NAME_FIR IS NULL))
    AND   (M_NAME = :NAME_MID OR (M_NAME IS NULL AND :NAME_MID IS NULL))
    AND   (L_NAME = :NAME_LAS OR (L_NAME IS NULL AND :NAME_LAS IS NULL))