我有三张桌子:
movies (MID, title)
actors (AID, name)
actor_role (MID, AID, roleName)
MID和AID是actor_role的外键。
我想将表格电影和演员的MID和AID数据插入到actor_roles中。 我使用以下代码:
insert into actor_role (rolename)
values
('aaaaa'),
('bbbbbbb'),
('ccccccccc'),
('ddd');
insert into actor_role (MID)
select MID from movies;
insert into actor_role (AID)
select AID from actors;
我收到了一个错误:
Msg 515, Level 16, State 2, Line 1
Cannot insert the value NULL into column 'MID', table 'MOVIE.dbo.actor_role'; column does not allow nulls. INSERT fails.
The statement has been terminated.
Msg 515, Level 16, State 2, Line 8
Cannot insert the value NULL into column 'rolename', table 'MOVIE.dbo.actor_role'; column does not allow nulls. INSERT fails.
The statement has been terminated.
Msg 515, Level 16, State 2, Line 11
Cannot insert the value NULL into column 'rolename', table 'MOVIE.dbo.actor_role'; column does not allow nulls. INSERT fails.
The statement has been terminated.
我如何解决错误?
答案 0 :(得分:1)
将最后两个插入查询合并为一个:
insert into actor_role (MID, AID)
select MID, AID
from actors cross join movies;
然后,根据需要更新角色名称。
如果查询抱怨rolename
列的空值,请在那里添加空格,直到您可以更新它....
insert into actor_role (MID, AID, rolename)
select MID, AID, ''
from actors cross join movies;
答案 1 :(得分:1)
那里有很多问题:
roleName
和MID
不接受null
值。这就是为什么在尝试插入Cannot insert the value NULL into column...
时始终收到消息actor_role
而未指定其中任何一列的内容。INSERT
语句对其进行更新。这永远不会奏效。要实现这样的目标,您必须执行INSERT
,然后执行UPDATE
。所以解决方案是使用单个INSERT
语句。类似的东西:
insert into actor_role (MID, AID, rolename)
values
(MID1, AID, 'aaaaa'),
(MID2, AID, 'bbbbbbb'),
(MID3, AID, 'ccccccccc'),
(MID4, AID, 'ddd');
AID
的位置,我想,actors
和MIDx
中的演员的PK是movies
中电影的PK。
修改强>
借用Charles解决方案,您可以通过执行以下操作来欺骗NOT NULL
上的rolename
约束:
insert into actor_role (MID, AID, rolename)
select MID, AID, "to complete..."
from actors cross join movies;
然后手动完成rolename列。