ALTER TABLE 语句与 FOREIGN KEY 约束冲突

2022-01-20 00:00:00 sql database foreign-keys sql-server

为什么在tblDomare表中添加外键会导致这个错误?

Why does add a foreign key to the tblDomare table result in this error?

ALTER TABLE 语句与 FOREIGN KEY 约束FK__tblDomare__PersN__5F7E2DAC"冲突.冲突发生在数据库almu0004"、表dbo.tblBana"、列BanNR"中.

The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK__tblDomare__PersN__5F7E2DAC". The conflict occurred in database "almu0004", table "dbo.tblBana", column 'BanNR'.

代码

CREATE TABLE tblDomare
(PersNR VARCHAR (15) NOT NULL,
fNamn VARCHAR (15) NOT NULL,
eNamn VARCHAR (20) NOT NULL,
Erfarenhet VARCHAR (5),
PRIMARY KEY (PersNR));

INSERT INTO tblDomare (PersNR,fNamn,eNamn,Erfarenhet)
Values (6811034679,'Bengt','Carlberg',10);

INSERT INTO tblDomare (PersNR,fNamn,eNamn,Erfarenhet)
Values (7606091347,'Josefin','Backman',4);

INSERT INTO tblDomare (PersNR,fNamn,eNamn,Erfarenhet)
Values (8508284163,'Johanna','Backman',1);

CREATE TABLE tblBana
(BanNR VARCHAR (15) NOT NULL,
PRIMARY KEY (BanNR));

INSERT INTO tblBana (BanNR)
Values (1);

INSERT INTO tblBana (BanNR)
Values (2);

INSERT INTO tblBana (BanNR)
Values (3);

ALTER TABLE tblDomare
ADD FOREIGN KEY (PersNR)
REFERENCES tblBana(BanNR);

推荐答案

这是因为您尝试创建一个从 tblDomare.PersNRtblBana.BanNR 的外键,但是/并且 tblDomare.PersNR 中的值与 tblBana.BanNR 中的任何值都不匹配.您不能创建违反参照完整性的关系.

It occurred because you tried to create a foreign key from tblDomare.PersNR to tblBana.BanNR but/and the values in tblDomare.PersNR didn't match with any of the values in tblBana.BanNR. You cannot create a relation which violates referential integrity.

相关文章