Create table APPLICANT
(
Applicant_ID varchar(10) NOT NULL,
Applicant_Name nvarchar (25) NOT NULL,
Father_Name nvarchar (25),
Gender nvarchar (15),
Applicant_DOB datetime,
Qualifaction nvarchar (45),
Application_Id varchar (15),
PRIMARY KEY (Applicant_ID, Applicant_Name)
);
create table APPLICATION
(
Application_ID varchar (10),
Application_Name nvarchar(25),
Applicant_ID varchar (10),
Applicant_Name nvarchar (25),
primary key (Application_ID)
);
Create table CELL_NUMBER
(
Cell_No varchar (15) NOT NULL ,
Applicant_ID varchar (10),
Applicant_Name nvarchar (25),
Primary Key (Cell_No)
);
Alter table CELL_NUMBER
add constraint fk_applicant_id foreign key (Applicant_ID) references APPLICANT (Applicant_ID);
Alter table CELL_NUMBER
ADD CONSTRAINT fk_applicant_name foreign key (Applicant_Name) references APPLICANT (Applicant_Name);
显示此错误
Msg 1776, Level 16, State 0, Line 34
There are no primary or candidate keys in the referenced table 'APPLICANT' that match the referencing column list in the foreign key 'fk_applicant_id'.
Msg 1750, Level 16, State 0, Line 34
Could not create constraint. See previous errors.
答案 0 :(得分:1)
您无法创建仅引用主键对的一列的外键。
Alter table CELL_NUMBER ADD CONSTRAINT fk_applicant
foreign key (Applicant_ID, Applicant_Name) references
APPLICANT (Applicant_ID, Applicant_Name)
这是因为您的外键需要在APPLICANT表中标识一行,并且由于您的主键引用了两列,因此您不能只使用一列来生成外键。 < / p>
编辑:您只能引用复合主键的一列,由Justin更正
答案 1 :(得分:0)
两列(外键和引用键)的数据类型必须完全匹配。由于Applicant_Name
中的nvarchar(25) NOT NULL
被定义为APPLICANT
,因此必须在CELL_NUMBER
中定义NOT NULL
({{1}}是缺失的部分)。