【问题标题】:Oracle if value to be inserted in foreign key is -1, insert null insteadOracle如果要插入外键的值为-1,则插入null
【发布时间】:2020-06-02 07:16:27
【问题描述】:

我有一个正在读取的 xml 脚本,用于在我的数据库中填充数据。 xml 文件中的一个节点没有 idDirector 字段(节点是电影),因此 xml 读取 -1 作为 idDirector 然后我的存储过程尝试将 -1 插入 fk 字段,这使我的数据库返回约束错误:director 表中不存在director -1。我怎样才能使它插入 null 并使我的 fk 字段可以为空?

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

谢谢

【问题讨论】:

    标签: sql oracle oracle11g oracle-sqldeveloper


    【解决方案1】:

    在我看来像CASE,例如

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

    它会起作用吗?是的:

    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.
    

    插入-1失败:

    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
    

    插入 NULL 有效:

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

    【讨论】:

    • 谢谢,我需要添加什么来让我的 fk 字段接受空值还是这已经是默认行为?
    • 不客气。不,你不必做任何事情。 NULL 将被接受。我添加了一个例子;看看吧。
    • @Johnny Bra:只要您没有使用 NOT NULL 声明明确禁止外键列,就可以为空。
    • nullif(id_director, -1) 也会这样做。
    猜你喜欢
    • 2018-04-13
    • 2011-10-28
    • 2019-01-21
    • 1970-01-01
    • 2012-06-07
    • 2015-03-22
    • 2018-01-09
    • 2013-08-06
    • 2016-10-23
    相关资源
    最近更新 更多