0

I'm making a foreign key but I don't understand why it won't work

Msg 1776, Level 16, State 0, Line 1 There are no primary or candidate keys in the referenced table 'dbo.QLKeSach' that match the referencing column list in the foreign key 'fk_QLKeSach_QLKeSach'. Msg 1750, Level 16, State 0, Line 1 Could not create constraint. See previous errors.

Like this:

create table QLKeSach
(
MaKeSach varchar(10) not null,
TenKeSach char(10) not null,
MaTang varchar(10) not null,
MaNgan varchar(10) not null,
MaKho varchar(10) not null,
)
create table QLTangSach
(
MaTang varchar(10) not null,
TenTang char(30) not null,
MaKeSach varchar(10) not null,
)

I created them but it gives an error

ALTER TABLE dbo.QLKeSach
ADD CONSTRAINT fk_QLKeSach
FOREIGN KEY (MaTang)
REFERENCES dbo.QLTangSach(MaTang);

David Browne - Microsoft
  • 80,331
  • 6
  • 39
  • 67
  • 3
    You need to define a primary key if possible on the QLKeSach table. The FK concept relies upon being able to find a single record, not a set of records, when looking for the related record. There might be more than one set of columns that can be a primary key. If a PK is already defined, consider a unique index on candidate keys. With a PK, only on record can have a null value for the PK columns. – Randy in Marin Jul 14 '22 at 01:12
  • MySQL <> SQL Server - please correct your tags. – Dale K Jul 14 '22 at 01:16
  • Correction. PK cannot have null values. A unique index can have nulls; however, nulls can be only exist uniquely. For example, a single column unique index can't have two records with a null in that column. For more columns, no two records can have the same combination of nulls and values. – Randy in Marin Jul 14 '22 at 01:29

0 Answers0