Creating a composite foreign key in SQL Server 2008

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)