Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare null value in PLSQL

Below is my code.

One variable is NOT having value. Another variable is having a value. In the below code, I want to print that the variables are not same even in the case when var1 is not having any value. How can I do that?

CREATE OR REPLACE PACKAGE BODY mypackagebody IS

 PROCEDURE comparenull() IS
  l_var1 mytable.mycolumn1%TYPE;
  l_var2 mytable.mycolumn2%TYPE;

 BEGIN
  BEGIN
   SELECT var1
         ,var2
   INTO   l_var1
         ,l_var2
   FROM   mytable;
  EXCEPTION
   WHEN no_data_found THEN
    var1 := NULL;
    var2 := NULL;
  END;

  /* At this point var1 is NOT having any value and var2 is having a value.*/
  /* The below if condition is returing false. But, I wanted to go inside the if condition and print that the var values are not same*/
  IF var1 <> var2
  THEN
   dbms_ouput.put_line('var1 and var2 are not same');

  END IF;

 END comparenull;

END mypackagebody;
like image 618
user2488578 Avatar asked Aug 17 '26 06:08

user2488578


2 Answers

I think you want a NULL-safe comparison. In Oracle, you can use multiple conditions:

IF var1 <> var2 OR
   (var1 is null and var2 is not null) OR
   (var1 is not null and var2 is null)
like image 196
Gordon Linoff Avatar answered Aug 18 '26 20:08

Gordon Linoff


Probably the most sucinct way of handling this is by using NVL

if NVL(var1, 'NULL') <> NVL(var2, 'NULL')

NVL will evaluate the variable and if it is null use the string in the comparison instead this string can be whatever you want it doesn't have to be the literal string NULL I just find this useful.

like image 37
Shaun Peterson Avatar answered Aug 18 '26 18:08

Shaun Peterson