简体   繁体   中英

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
Foreign key 'company_enumber_FK' references invalid column 'enumber' in referencing table 'company'.
Msg 1750, Level 16, State 0, Line 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.

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

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.

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 .

Finally, you can alter Company again to change the nullable column to be NOT NULL .

This means the Company doesn't have a field named enumber . So in other words, this:

ADD FOREIGN KEY (enumber)

is referencing the wrong field in Company .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM