Sql – Creating a composite foreign key in SQL Server 2008

sqlsql-server-2008

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

Primary Table

PK - Key1 - varchar(20)
PK - Key2 - date

Secondary Table

PK - AutoID
FK - Key1 - varchar(20)
FK - Key2 - date

When I try to create the relationship between the primary and secondary table, I keep getting the message

The columns in the Primary Table do not match a primary key or unique
constraint.

There can be many records in the secondary table with the same Key1 and Key2 so we made the primary key an auto created number.

Any thoughts on how I can set up the foreign key relationship between these two tables?

Best Answer

A foreign key MUST refer to columns that compose a unique index (PK or UK) with the same number of column, their types and order. E.g.:

CREATE TABLE PrimaryTable (
  Key1 varchar(20),
  Key2 date)
GO

ALTER TABLE PrimaryTable ADD CONSTRAINT PK
  PRIMARY KEY (Key1, Key2)
GO

CREATE TABLE SecondaryTable (
  AutoID int IDENTITY,
  Key1 varchar(20),
  Key2 date)
GO

ALTER TABLE SecondaryTable ADD CONSTRAINT FK
  FOREIGN KEY (Key1, Key2) REFERENCES PrimaryTable (Key1, Key2)
GO