SQL将外键添加到现有列


110

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

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

UserID是我在Employees表格中的FK列。我正在尝试UserIDActiveDirectories表格中引用。我收到此错误:

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


1
您能提供两个表格的架构吗?
Stefan

Answers:


191

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

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

这是正确的。我们的数据库未更新我们的添加列。此问题已解决,但不是我们的专栏已建立,我仍然无法添加约束。There are no primary or candidate keys in the referenced table 'ActiveDirectories' that match the referencing column list in the foreign key 'FK__Employees__UserI__04E4BC85'.
ExceptionLimeCat

看起来FK__Employees__UserI__04E4BC85所引用的任何列都未定义为ActiveDirectories表中的PRIMARY KEY或候选键。
BluesRockAddict 2012年

是的,但这绝对是我们在ActiveDirectories表中的PK
ExceptionLimeCat

1
解决:有一个原因导致您在构建之前创建ERD并建立关系。我们在一个表中有太多记录,这导致尝试创建与另一表的关系时出错。谢谢大家
ExceptionLimeCat


19

也许您的专栏文章倒退了??

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

难道列被称为IDEmployees表,UserIDActiveDirectories表?

然后您的命令应该是:

ALTER TABLE Employees
ADD FOREIGN KEY (ID)                   <-- column in table "Employees"
REFERENCES ActiveDirectories(UserID)   <-- column in table "ActiveDirectories" 

1
我知道它的怪异,但不幸的是,名称中的ActiveDirectory表ID
ExceptionLimeCat

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)

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

5
您应该用答案提供一些解释
fen1x


0

在将来。

ALTER TABLE Employees
ADD UserID int;

ALTER TABLE Employees
ADD CONSTRAINT FK_ActiveDirectories_UserID FOREIGN KEY (UserID)
    REFERENCES ActiveDirectories(id);
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.