Oracle PL/SQL string compare issue

前端 未结 7 1121
予麋鹿
予麋鹿 2020-12-24 14:16

I have the following Oracle PL/SQL codes that may be rusty from you guys perspective:

 DECLARE
 str1  varchar2(4000);
 str2  varchar2(4000);
 BEGIN
   str1:         


        
7条回答
  •  时光取名叫无心
    2020-12-24 14:41

    As Phil noted, the empty string is treated as a NULL, and NULL is not equal or unequal to anything. If you expect empty strings or NULLs, you'll need to handle those with NVL():

     DECLARE
     str1  varchar2(4000);
     str2  varchar2(4000);
     BEGIN
       str1:='';
       str2:='sdd';
    -- Provide an alternate null value that does not exist in your data:
       IF(NVL(str1,'X') != NVL(str2,'Y')) THEN
        dbms_output.put_line('The two strings are not equal');
       END IF;
     END;
     /
    

    Concerning null comparisons:

    According to the Oracle 12c documentation on NULLS, null comparisons using IS NULL or IS NOT NULL do evaluate to TRUE or FALSE. However, all other comparisons evaluate to UNKNOWN, not FALSE. The documentation further states:

    A condition that evaluates to UNKNOWN acts almost like FALSE. For example, a SELECT statement with a condition in the WHERE clause that evaluates to UNKNOWN returns no rows. However, a condition evaluating to UNKNOWN differs from FALSE in that further operations on an UNKNOWN condition evaluation will evaluate to UNKNOWN. Thus, NOT FALSE evaluates to TRUE, but NOT UNKNOWN evaluates to UNKNOWN.

    A reference table is provided by Oracle:

    Condition       Value of A    Evaluation
    ----------------------------------------
    a IS NULL       10            FALSE
    a IS NOT NULL   10            TRUE        
    a IS NULL       NULL          TRUE
    a IS NOT NULL   NULL          FALSE
    a = NULL        10            UNKNOWN
    a != NULL       10            UNKNOWN
    a = NULL        NULL          UNKNOWN
    a != NULL       NULL          UNKNOWN
    a = 10          NULL          UNKNOWN
    a != 10         NULL          UNKNOWN
    

    I also learned that we should not write PL/SQL assuming empty strings will always evaluate as NULL:

    Oracle Database currently treats a character value with a length of zero as null. However, this may not continue to be true in future releases, and Oracle recommends that you do not treat empty strings the same as nulls.

提交回复
热议问题