Reputation: 4575
I always find it confusing to add foreign keys to primary table in Management Studio.
Lets say I have a
Table1
{
ID int, -- Primary Key
Table2ID int, -- Refers to Table2's ID
}
Table2
{
ID int, -- Primary Key
SomeData nvarchar(50)
}
I am adding a foreign key to Table1 by Right Click -> Relationships -> Table and column specification
. I am setting "Primary" popups to Table2, ID and "Foreign Key Table" to Table1, Table2ID.
My questions:
Shouldn't Table2 be listed for "Foreign Key Table" and Table1 for Primary Key? Is my understanding wrong?
When I save I get an alert "The following tables will be saved to your database." and it shows both tables. I really don't get this. I only changed Table1. Why is the second table shown?
Upvotes: 49
Views: 102356
Reputation: 11580
Follow this way to create a foreign key in your table.
Upvotes: 8
Reputation: 2607
Upvotes: 109
Reputation: 643
ALTER TABLE dbo.Table1
ADD CONSTRAINT FK_Table1_Table2
FOREIGN KEY(Table2ID) REFERENCES dbo.Table2(ID)
Upvotes: 1
Reputation: 13965
1.Shouldn't Table2 be listed for "Foreign Key Table" and Table1 for Primary Key? Is my understanding wrong?
I believe your understanding is wrong. Table2 is the table whose primary key you are referencing. Therefore it's listed under Primary Key. Table1 is the table that will have the foreign key (the reference to the primary key of another table); therefore it's listed under "Foreign Key Table".
As far as why both tables are saved, even though the foreign key is listed afterward as belonging to Table1: I believe it's because the foreign key constrains both tables. They both have to "know" about the constraint, so they both need to be saved.
Upvotes: 9
Reputation: 754488
Why don't you just use the equivalent T-SQL statements?? Seems much easier and less confusing to me:
ALTER TABLE dbo.Table1
ADD CONSTRAINT FK_Table1_Table2
FOREIGN KEY(Table2ID) REFERENCES dbo.Table2(ID)
When I read this, I believe this is immediately clear what two tables are involved, and how they are connected (Table1.Table2ID
--(references)--> Table2.ID
)
If you want to stay in the SSMS designer world: you could also create a database diagram of your tables involved, and then just drag&drop your Table2ID
column from Table1
over to Table2
and drop it onto the ID
column there - this would graphically tell SSMS what you want to do, and you just need to review your choices and click OK on the dialog that pops up.
Upvotes: 25