简体   繁体   English

添加外键时SQL Server中的错误

[英]Error in SQL Server while adding foreign key

There are no primary or candidate keys in the referenced table 'Employee' that match the referencing column list in the foreign key. 在引用表“ Employee”中没有与外键中的引用列列表匹配的主键或候选键。

I have already set my reference as primary key, but still getting the error. 我已经将我的引用设置为主键,但是仍然出现错误。

 Create table Employee 
 (
     Fname varchar(20),
     Mint varchar(1),
     Lname varchar(20),
     Ssn int,
     Bdat date,
     [Address] varchar(50),
     Sex varchar(1),
     Salary int,
     Super_ssn int,
     Dno int
)

Create table Department   
(
     Dname varchar(20),
     Dnumber int,
     Mgr_ssn int,
     Mgr_start_date date
)

Alter table Employee
alter column Ssn int NOT NULL
alter column Super_ssn int NOT NULL

alter table Employee
add primary key (Ssn, Super_ssn)

alter table Department 
add foreign key (Mgr_ssn) 
    References Employee (Ssn)

You have a composite PK in your Employees table ( Ssn, Super_ssn ), but you try to reference it with one column ( Mgr_ssn ). 您的雇员表中有一个复合PK( Ssn, Super_ssn ),但是您尝试用一个列( Mgr_ssn )来引用它。

Either change the PK to Ssn only, or add another column to the foreign key. 将PK更改为仅Ssn ,或将另一列添加到外键。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM