SQL将外键添加到现有列 [英] SQL Add foreign key to existing column

查看:167
本文介绍了SQL将外键添加到现有列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

Employees 表中, UserID 是我的FK列。我试图在我的 ActiveDirectories 表中引用 UserID 。我收到这个错误:
$ b


外键UserID在引用
表'Employees'时引用无效列'UserID' / p>


解决方案

错误表示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);

这篇关于SQL将外键添加到现有列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆