views:

24

answers:

1

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:

  1. Shouldn't Table2 be listed for "Foreign Key Table" and Table1 for Primary Key? Is my understanding wrong?

  2. 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?

A: 

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.

marc_s
tvr