且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

SQL将外键添加到现有列

更新时间:2023-11-30 23:33:34

错误表示Employees表中没有UserID列。尝试添加列,然后重新运行语句。

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


If I am using the following SQL command in SQL Server 2008 to update a table with a foreign key constraint:

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

UserID being my FK column in the Employees table. I'm trying to reference the UserID in my ActiveDirectories table. I receive this error:

Foreign key 'UserID' references invalid column 'UserID' in referencing table 'Employees'.

Error indicates that there is no UserID column in your Employees table. Try adding the column first and then re-run the statement.

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