119

如果我在 SQL Server 2008 中使用以下 SQL 命令来更新具有外键约束的表:

ALTER TABLE Employees
ADD FOREIGN KEY (UserID)
REFERENCES ActiveDirectories(id)

UserID是我在表中的 FK 列Employees。我试图UserID在我的ActiveDirectories表中引用。我收到此错误:

外键“UserID”在引用表“Employees”中引用了无效列“UserID”。

4

7 回答 7

204

错误表明您的员工表中没有 UserID 列。尝试先添加列,然后重新运行语句。

ALTER TABLE Employees
ADD CONSTRAINT FK_ActiveDirectories_UserID FOREIGN KEY (UserID)
    REFERENCES ActiveDirectories(id);
于 2012-04-30T19:37:34.353 回答
22

也许你的列倒了?

ALTER TABLE Employees
ADD FOREIGN KEY (UserID)           <-- this needs to be a column of the Employees table
REFERENCES ActiveDirectories(id)   <-- this needs to be a column of the ActiveDirectories table

难道是在表中调用ID了该Employees列,并且UserIDActiveDirectories表中?

那么你的命令应该是:

ALTER TABLE Employees
ADD FOREIGN KEY (ID)                   <-- column in table "Employees"
REFERENCES ActiveDirectories(UserID)   <-- column in table "ActiveDirectories" 
于 2012-04-30T19:39:31.677 回答
5

MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE Orders
ADD FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id)

要允许命名 FOREIGN KEY 约束并在多个列上定义 FOREIGN KEY 约束,请使用以下 SQL 语法:

MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE Orders
ADD CONSTRAINT fk_PerOrders
FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id)
于 2015-06-23T13:11:19.487 回答
2

在将来。

ALTER TABLE Employees
ADD UserID int;

ALTER TABLE Employees
ADD CONSTRAINT FK_ActiveDirectories_UserID FOREIGN KEY (UserID)
    REFERENCES ActiveDirectories(id);
于 2018-05-24T00:50:11.860 回答
1
ALTER TABLE Faculty 
WITH CHECK ADD  CONSTRAINT FKFacultyBook
FOREIGN KEY FacId
REFERENCES Book Book_Id

ALTER TABLE Faculty 
WITH CHECK ADD  CONSTRAINT FKFacultyStudent 
FOREIGN KEY FacId
REFERENCES Student StuId
于 2017-09-14T05:57:04.803 回答
0

ActiveDirectories(id)的外键创建方式正确,我认为主要错误是您没有在ActiveDirectories表中提到id的主键

于 2016-12-01T10:59:55.550 回答
0

如果表已经创建:

首先做:

ALTER TABLE `table1_name` ADD UNIQUE( `column_name`);

然后:

ALTER TABLE `table1_name` ADD FOREIGN KEY (`column_name`) REFERENCES `table2_name`(`column_name`);
于 2020-11-20T20:08:48.257 回答