Creating a composite foreign key in SQL Server 2008

后端 未结 5 1646
旧时难觅i
旧时难觅i 2020-12-05 17:35

I have two tables that I\'d like to create a foreign key for.

Primary Table

PK - Key1 - varchar(20)
PK - Key2 - date
5条回答
  •  广开言路
    2020-12-05 17:57

    There are some good answers here, but I would like to take this a step further - for the sake of posterity.

    A foreign key does have to reference either a Primary key (Unique, Clustered Index) or a Unique constrained column in another table. Basically, the necessary component is the Unique constraint. I would add that you can have nullable columns in your foreign key, BUT if you do allow nulls in a "composite" key SQL skips the verification of the data in the foreign key relationship. This is an important point to remember as the main reason most of us use foreign keys is to ensure data integrity across our databases.

    On a final note, I like to explicitly declare all my key names. Why, you might ask? If you need to use "Full-Text Indexing" in the future for better search capabilities, not doing so forces you to reference all the "auto-generated" names of the keys. This may not be a big deal for small projects that do not require data transformation or scheduled Full-Text index updates, but if you are scripting this functionality you could make your job more difficult (e.g. having to look up the actual name of your Primary Key's default name: pk_someTable_1248594832828495904).

    Here is what I would do in writing the SQL to avoid any future pitfalls:

    1. Do not allow NULLs on Composite foreign keys if possible.
    2. Name keys explicitly using an agreed upon naming convention (e.g. PK_Schema/56_TalbeName_Col1_Col2). Not only does this give you a standard name for the key, but you can easily see from the index what columns are referenced and in which order.

    The Code:

    CREATE TABLE MySchema.PrimaryTable ( 
      Key1 varchar(20) NOT NULL, 
      Key2 date NOT NULL,
      CONSTRAINT PK_MySchema_PrimaryTable_Key1_Key2 PRIMARY KEY (Key1, Key2)
    )
    GO 
    
    CREATE TABLE MySchema.SecondaryTable ( 
      AutoID int IDENTITY, 
      Key1 varchar(20) NOT NULL, 
      Key2 date NOT NULL,
      CONSTRAINT FK_MySchema_SecondaryTable_Key1_Key2
         FOREIGN KEY (Key1, Key2) REFERENCES PrimaryTable (Key1, Key2)
    )
    GO 
    

    OptillectTeam is basically dead on with his answer. I just wanted to clarify a few important things that had not been mentioned before. There is a good reference on the MSDN sight discussing this and more on foreign keys: Foreign Key Constraint.

提交回复
热议问题