INSERT因ORA-01400失败:无法插入NULL

时间:2018-01-04 20:04:21

标签: sql oracle

我正在使用ORACLE SQL Developer,我创建了一个id为PK的表,另一个FK,id_columnx和column1,并将数据插入其中。然后我添加了另外2列,第2列和第3列,当我尝试将数据插入这些新添加的列时,我收到错误:

  

ORA-01400:无法插入NULL。

我必须提到我在表上没有任何触发器,并且我在INSERT语句中有值。似乎与PK id有冲突,但我不明白为什么。 所以这是代码:

create table mytable(id INT PRIMARY KEY, name varchar2(30));

insert into mytable values (1, 'Mary');
insert into mytable values (2, 'John');
insert into mytable values (3, 'Bill');

alter table mytable 
add email VARCHAR2(30);
alter table mytable 
add addess VARCHAR2(30);

insert into mytable (email, addess)
values ('mary@gmail.com', 'Street X');

这是我得到的错误:

Error starting at line : 12 in command -
insert into mytable (email, addess)
values ('mary@gmail.com', 'Street X')
Error report -
ORA-01400: cannot insert NULL into ("ZAMFIRESCUA_49"."MYTABLE"."ID")

2 个答案:

答案 0 :(得分:2)

INSERT用于插入新行,UPDATE用于更改当前行中的数据。正如评论中所提到的,看起来您想要用她的电子邮件/地址更新Mary的行:

UPDATE mytable
SET email = 'mary@gmail.com',
    address = 'Street X'
WHERE ID = 1 --Mary's ID for example, replace with the ID of the row you want to update

您还可以使用子查询来查找正确的ID,这样您就不必总是查找它:

UPDATE mytable
SET email = 'mary@gmail.com',
    address = 'Street X'
WHERE ID = (SELECT ID FROM mytable WHERE name = 'Mary')

编辑:

我在想这个答案时有两张桌子,你可以随时使用name字段作为过滤器:

UPDATE mytable
SET email = 'mary@gmail.com',
    address = 'Street X'
WHERE name = 'Mary'

答案 1 :(得分:1)

您在INSERT语句后的ALTER内错过了PK值。试试这个:

create table mytable(id INT PRIMARY KEY, name varchar2(30)); 

insert into mytable values (1, 'Mary'); 
insert into mytable values (2, 'John'); 
insert into mytable values (3, 'Bill'); 

alter table mytable add email VARCHAR2(30); 
alter table mytable add addess VARCHAR2(30); 

insert into mytable (id, email, addess) values (4, 'mary@gmail.com', 'Street X');