oracle如果要在外键中插入的值是-1,则插入null

yizd12fk  于 2021-08-09  发布在  Java
关注(0)|答案(1)|浏览(381)

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

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

谢谢您

aelbi1ox

aelbi1ox1#

看起来像 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

插入空作品:

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

1 row created.

SQL>

相关问题