Search code examples
sqloracleoracle11goracle-sqldeveloper

Oracle if value to be inserted in foreign key is -1, insert null instead


I have a xml script I'm reading from to populate my database with data. One of the nodes in the xml file don't have a idDirector field (the nodes are movies) and so the xml reads a -1 as idDirector and then my stored procedure tries to insert -1 into the fk field and this makes my database returna constraint error : director -1 doesn't exist in Director table. How can I make it so it inserts null instead and make my fk field nullable?

CREATE TABLE Film (
    PRIMARY KEY (idFilm),
    FOREIGN KEY (idDirector) REFERENCES Director
);

Thank you


Solution

  • Looks like CASE to me, e.g.

    insert into film (id_film, id_director)
    select id_film,
           case when id_director = -1 then null
                else id_director
           end
    from ...
    

    Will it work? Yes:

    SQL> create table director (id number primary key);
    
    Table created.
    
    SQL> create table film (id number primary key, id_director number references director);
    
    Table created.
    
    SQL> insert into director values (100);
    
    1 row created.
    

    Inserting -1 fails:

    SQL> insert into film (id, id_director) values (1, -1);
    insert into film (id, id_director) values (1, -1)
    *
    ERROR at line 1:
    ORA-02291: integrity constraint (SCOTT.SYS_C0065885) violated - parent key not
    found
    

    Inserting NULL works:

    SQL> insert into film (id, id_director) values (1, null);
    
    1 row created.
    
    SQL>