[英]adding a foreign key in sql server 2005
I am using the following command to add a foreign key 我正在使用以下命令添加外键
ALTER TABLE Company
ADD FOREIGN KEY (enumber)
REFERENCES emp(enumber);
... but it's giving an error: ...但是它给出了一个错误:
Msg 1769, Level 16, State 1, Line 2
消息1769,第16级,状态1,第2行
Foreign key 'company_enumber_FK' references invalid column 'enumber' in referencing table 'company'.外键“ company_enumber_FK”引用引用表“ company”中的无效列“ enumber”。
Msg 1750, Level 16, State 0, Line 2消息1750,级别16,状态0,第2行
Could not create constraint.无法创建约束。 See previous errors.
请参阅先前的错误。
Now if I create a column enumber
in table company
and execute it the command runs but shows null value. 现在,如果我在表
company
创建一列enumber
并执行该命令,则该命令将运行,但显示空值。
Here enumber
is a primary key of table emp
and company
is another table in which I want the foreign key enumber
to be added 这里
enumber
是表emp
的主键,而company
是另一个表,我希望在其中添加外键enumber
What should I do? 我该怎么办?
The usual approach would be to add the new column to the Company
table - either as a nullable column or (if all rows should receive the same value) with a default. 通常的方法是将新列添加到
Company
表-作为可为空的列或(如果所有行应接收相同的值)默认值。
Next, you apply the foreign key constraint. 接下来,应用外键约束。
If, in the first paragraph, you opted for the nullable column, you should now write an UPDATE
that determines what the correct value is for each row in Company
. 如果在第一段中选择了可为空的列,那么现在应该编写一个
UPDATE
来确定Company
每一行的正确值。
Finally, you can alter Company
again to change the nullable column to be NOT NULL
. 最后,您可以再次更改
Company
以将可为空的列更改为NOT NULL
。
This means the Company
doesn't have a field named enumber
. 这意味着
Company
没有名为enumber
的字段。 So in other words, this: 换句话说:
ADD FOREIGN KEY (enumber)
is referencing the wrong field in Company
. 在
Company
引用了错误的字段。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.