Monday, July 6, 2015

Can foreign key reference non primary key


  1. FOREIGN KEY constraint does not have to be linked only to aPRIMARY KEY constraint in another table; it can also be defined toreference the columns of a UNIQUE constraint in another table. So in your case if you make AnotherID unique, it will be allowed.
CREATE TABLE table3
(
   ID INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
   AnotherID INT NOT NULL,
   SomeData VARCHAR(100) NOT NULL
)

CREATE TABLE table4
(
   ID INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
   AnotherID INT NOT NULL,
   MoreData VARCHAR(30) NOT NULL,

   CONSTRAINT fk_table4_table3 FOREIGN KEY (AnotherID) REFERENCES table3 (AnotherID)
)

There are no primary or candidate keys in the referenced table 'table3' that match the referencing column list in the foreign key 'fk_table4_table3'.


/****** Object:  Table [dbo].[table1]    Script Date: 7/7/2015 11:28:36 AM ******/
CREATE TABLE table3
(
   ID INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
   AnotherID INT Unique NOT NULL,
   SomeData VARCHAR(100) NOT NULL
)

CREATE TABLE table4
(
   ID INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
   AnotherID INT NOT NULL,
   MoreData VARCHAR(30) NOT NULL,

   CONSTRAINT fk_table4_table3 FOREIGN KEY (AnotherID) REFERENCES table3 (AnotherID)
)





No comments:

Post a Comment