Oracle considers empty strings to be NULL while SQL Server does not - how is this best handled?

前端 未结 11 1877
挽巷
挽巷 2021-01-01 13:35

I have to write a component that re-creates SQL Server tables (structure and data) in an Oracle database. This component also has to take new data entered into the Oracle d

11条回答
  •  攒了一身酷
    2021-01-01 14:03

    Although, for the most part, I agree with most of the other responses (not going to get into an argument about any I disagree with - not the place for that :) )

    I do notice that OP mentioned the following:

    "Oracle considers a blank string to be the same as a NULL value, so if a char column is defined as NOT NULL, you cannot insert a blank string."

    Specifically calling out CHAR, and not VARCHAR2. Hence, talking about an "empty string" of length 0 (ie '' ) is moot. If he's declared the CHAR as, for example, CHAR(5), then just add a space to the empty string coming in, Oracle's going to pad it anyway. You'll end up with a 5 space string.

    Now, if OP meant VARCHAR2, well yeah, that's a whole other beast, and yeah, the difference between empty string and NULL becomes relevant.

      SQL> drop table junk;
    
      Table dropped.
    
      SQL>
      SQL> create table junk ( c1     char(5) not null );
    
      Table created.
    
      SQL>
      SQL> insert into junk values ( 'hi' );
    
      1 row created.
    
      SQL>
      SQL> insert into junk values ( ' ' );
    
      1 row created.
    
      SQL>
      SQL> insert into junk values ( '' );
      insert into junk values ( '' )
                                *
      ERROR at line 1:
      ORA-01400: cannot insert NULL into ("GREGS"."JUNK"."C1")
    
    
      SQL>
      SQL> insert into junk values ( rpad('', 5, ' ') );
      insert into junk values ( rpad('', 5, ' ') )
                                *
      ERROR at line 1:
      ORA-01400: cannot insert NULL into ("GREGS"."JUNK"."C1")
    
    
      SQL>
      SQL> declare
        2    lv_in   varchar2(5) := '';
        3  begin
        4     insert into junk values ( rpad(lv_in||' ', 5) );
        5  end;
        6  /
    
      PL/SQL procedure successfully completed.
    
      SQL>
    

提交回复
热议问题