外键的SQL错误

时间:2018-06-11 15:00:00

标签: sql sql-server

I have the error here:

  

INSERT语句与FOREIGN KEY约束“FK_CHITIETDH__MaDH__4316F928”冲突。冲突发生在数据库[...]

但是这里有代码:

create database abc_1quanly111
use abc_1quanly111

create table abc_1nhacc
(
    MaNhaCC   varchar(10) primary key,
    TenNhaCC  varchar(50),
    DiaChiCC  varchar(50),
    Telephone varchar(50),
)

create table abc_1mamathang
(
    MaMH   varchar(10) primary key,
    TenMH  varchar(50) not null,
    DonGia  int check (DonGia>0),
    SoLuong int ,
    MaNhaCC varchar(10) foreign key references abc_1nhacc(MaNhaCC)
)
--Insert Nha CC --- Values -----
INSERT INTO abc_1nhacc VALUES('NC1','Phong Vu','123 NTMK ','0283232677')
INSERT INTO abc_1nhacc VALUES('NC2','Phong Hoang','123 NTD ','0290120217'),('NC3','THE GIOI DI DONG','12 LE VAN VIET ','028382901'),('NC4','NGUYEN KIM','23 LE DUAN ','01283232677'),('NC5','Phong KIM','13 LE LOI ','0288292677')
select * from abc_1nhacc
--Insert Mat Hang ---- Values ----
insert into abc_1mamathang values('M1','Laptop Sony',1000000,100,'NC1')
,
('M2','Laptop MSI GAMING',3200000,1,'NC2'),
('M3','Laptop ASUS',900000,10,'NC3'),
('M4','Laptop ACER',1340000,20,'NC4'),
('M5','Xperia A',10000,10,'NC5')
select * from abc_1nhacc
select * from abc_1mamathang

create table abc_1khachhang
(
    MaKhachHang      varchar(10) primary key,
    TenKhachHang     varchar(50),
    DiaChiKhachHang  varchar(50),
    PhoneKhachHang   varchar(10),
)
--Insert Khach Hang ---- Values ----
INSERT INTO abc_1khachhang values('KH1','Anh A','121 Le Duan Q1','09878721'),('KH2','Anh B','12 Quang Trung Q12','01878221'),('KH3','Anh C','331 Nguyen Thi Minh Khai','028787221'),('KH4','Anh D','23 Le Quang Dinh','09872321'),('KH5','Bac AD','','098787211')


create table abc_1dondathang
(
    MaSoDonDatHang varchar(10) primary key,
    NgayDatHang    DATE Default GetDate(),
    MaKhachHang varchar(10) foreign key references abc_1khachhang(MaKhachHang)
)
CREATE TABLE CHITIETDH
(
     MaDH varchar(10) foreign key references abc_1dondathang,
     MaMH varchar(10) foreign key references abc_1mamathang,
      Soluong int check (soluong>0)
      constraint pk_DHMH primary key(MaDH ,MaMH)
)

select * from abc_1dondathang
select * from abc_1mamathang
select * from CHITIETDH

insert into CHITIETDH values('DH1','MH1',12) // errors

select * from CHITIETDH

我不知道解决方法如何解决这个问题,任何人都可以帮助我。

1 个答案:

答案 0 :(得分:0)

您的表CHITIETDH在表abc_1dondathang中有一个外键。 当CHITIETDH为空时,您尝试将值插入abc_1dondathang。在MaDH varchar(10) foreign key references abc_1dondathang中插入内容之前,您必须在abc_1dondathang列中包含此列CHITIETDH下的所有值。

您可以阅读更多here