Foreign key referencing a 2 columns primary key in SQL Server
Of course it's possible to create a foreign key relationship to a compound (more than one column) primary key. You didn't show us the statement you're using to try and create that relationship - it should be something like:
ALTER TABLE dbo.Content ADD CONSTRAINT FK_Content_Libraries FOREIGN KEY(LibraryID, Application) REFERENCES dbo.Libraries(ID, Application)
Is that what you're using?? If (ID, Application)
is indeed the primary key on dbo.Libraries
, this statement should definitely work.
Luk: just to check - can you run this statement in your database and report back what the output is??
SELECT tc.TABLE_NAME, tc.CONSTRAINT_NAME, ccu.COLUMN_NAMEFROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tcINNER JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE ccu ON ccu.TABLE_NAME = tc.TABLE_NAME AND ccu.CONSTRAINT_NAME = tc.CONSTRAINT_NAMEWHERE tc.TABLE_NAME IN ('Libraries', 'Content')
Note that the fields must be in the same order. If the Primary Key you are referencing is specified as (Application, ID) then your foreign key must reference (Application, ID) and NOT (ID, Application) as they are seen as two different keys.
The key is "the order of the column should be the same"
Example:
create Table A ( A_ID char(3) primary key, A_name char(10) primary key, A_desc desc char(50))create Table B ( B_ID char(3) primary key, B_A_ID char(3), B_A_Name char(10), constraint [Fk_B_01] foreign key (B_A_ID,B_A_Name) references A(A_ID,A_Name))
the column order on table A should be --> A_ID
then A_Name
; defining the foreign key should follow the same order as well.