插入数据时与外键约束冲突

时间:2018-12-04 07:49:33

标签: sql-server

这些是我的表,它们是已创建的,但是当我在AMI表中插入数据时,它给了我外键冲突错误。我了解插入子表之前,父表应具有该值。在这里,我的AMI表既依赖于household_income,也依赖于location,并且都具有数据。那么为什么我得到错误:

Insert into AMI values('CONTROL','ZIP','PER','L30','L50','L80');
  

消息547,级别16,状态0,第1行INSERT语句与> FOREIGN KEY约束“ FK__AMI__7908F585”相冲突。数据库>“ mydatabase_old”的表“ dbo.household_income”中发生了冲突。   该声明已终止。

create table admin
(control   varchar(15), 
status     varchar(3),
weight     float(24),
metro3     varchar(3),
PRIMARY KEY (control)
);



create table AMI 
(control varchar(15),
zip    varchar(8),
per     VARCHAR(15),
L30         int,
L50         int,
L80         int,
PRIMARY KEY(zip, per),
foreign key (zip, control) references location on delete cascade,
foreign key (per, control) references household_income ON UPDATE NO ACTION
);



create table location
(region varchar(5),
control   varchar(15),
zip    varchar(8),
PRIMARY KEY(zip, control),
foreign key (control) references admin on delete cascade
);


create table household_income
(control   varchar(15),
age1    int,
per    varchar(15),
ownrent     varchar(3),
totalsal    float(24),
zinc2       float(24),
type        varchar(15), 
PRIMARY KEY(control, per),
foreign key (control) references admin on delete cascade,
foreign key (type, control) references structure ON UPDATE NO ACTION,
);

1 个答案:

答案 0 :(得分:0)

首先您需要插入位置表

然后进入family_income

然后插入

Insert into AMI values('CONTROL','ZIP','PER','L30','L50','L80');