如果我在SQL Server 2008中使用以下SQL命令来更新具有外键约束的表:
ALTER TABLE Employees
ADD FOREIGN KEY (UserID)
REFERENCES ActiveDirectories(id)
UserID
是Employees
表中的FK列。我正在尝试在UserID
表格中引用 ActiveDirectories
。我收到此错误:
外键'UserID'在引用时引用了无效的列'UserID' 表'员工'。
答案 0 :(得分:176)
错误表示Employees表中没有UserID列。首先尝试添加列,然后重新运行该语句。
ALTER TABLE Employees
ADD CONSTRAINT FK_ActiveDirectories_UserID FOREIGN KEY (UserID)
REFERENCES ActiveDirectories(id);
答案 1 :(得分:17)
也许你倒退了你的专栏?
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
和UserID
表中的ActiveDirectories
?
然后你的命令应该是:
ALTER TABLE Employees
ADD FOREIGN KEY (ID) <-- column in table "Employees"
REFERENCES ActiveDirectories(UserID) <-- column in table "ActiveDirectories"
答案 2 :(得分:2)
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)
答案 3 :(得分:1)
如果已创建表:
首先要做:
ALTER TABLE `table1_name` ADD UNIQUE( `column_name`);
然后:
ALTER TABLE `table1_name` ADD FOREIGN KEY (`column_name`) REFERENCES `table2_name`(`column_name`);
答案 4 :(得分:0)
外键创建的方式对于ActiveDirectories(id)是正确的,我认为主要的错误是你没有在ActiveDirectories表中提到id的主键
答案 5 :(得分:0)
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
答案 6 :(得分:0)
将来。
ALTER TABLE Employees
ADD UserID int;
ALTER TABLE Employees
ADD CONSTRAINT FK_ActiveDirectories_UserID FOREIGN KEY (UserID)
REFERENCES ActiveDirectories(id);