Reputation: 6883
I have two tables - Educators and Faculties:
CREATE TABLE [dbo].[Educators]
(
[UserId] [nvarchar](128) NOT NULL,
[FacultyId] [smallint] NOT NULL,
[InstitutionUserId] [nvarchar](128) NOT NULL,
CONSTRAINT [PK_Educators]
PRIMARY KEY CLUSTERED ([UserId] ASC)
)
CREATE TABLE [dbo].[Faculties]
(
[InstitutionUserId] [nvarchar](128) NOT NULL,
[FacultyId] [smallint] NOT NULL,
CONSTRAINT [PK_UserFaculties]
PRIMARY KEY CLUSTERED ([InstitutionUserId] ASC, [FacultyId] ASC)
)
The table Faculties
has a compound primary key made up from two columns (InstitutionUserId
and FacultyId
). I also have the same column in the Educators
table. I want to link those two tables together with a foreign key.
So, this is my query:
ALTER TABLE [dbo].[Educators] WITH CHECK
ADD CONSTRAINT [FK_Educators_FacultyId_Faculties_FacultyId]
FOREIGN KEY ([FacultyId], [InstitutionUserId])
REFERENCES [dbo].[Faculties] ([FacultyId], [InstitutionUserId])
But I getting this error message:
Msg 1776, Level 16, State 0, Line 7
There are no primary or candidate keys in the referenced table 'dbo.Faculties' that match the referencing column list in the foreign key 'FK_Educators_FacultyId_Faculties_FacultyId'.Msg 1750, Level 16, State 1, Line 7
Could not create constraint or index. See previous errors.
How to solve this problem?
Upvotes: 0
Views: 502
Reputation: 1594
Your tables and their constraints look fine. The only issue I can see is that the order of the columns in your primary key
CONSTRAINT [PK_UserFaculties] PRIMARY KEY CLUSTERED
(
[InstitutionUserId] ASC,
[FacultyId] ASC
)
is different from the order that you've declared in your foreign key constraint
ALTER TABLE [dbo].[Educators] WITH CHECK ADD CONSTRAINT [FK_Educators_FacultyId_Faculties_FacultyId] FOREIGN KEY([FacultyId], [InstitutionUserId])
REFERENCES [dbo].[Faculties] ([FacultyId], [InstitutionUserId])
Try changing the order of the columns in the declaration of your foreign key like this:
ALTER TABLE [dbo].[Educators] WITH CHECK ADD CONSTRAINT [FK_Educators_FacultyId_Faculties_FacultyId] FOREIGN KEY([InstitutionUserId], [FacultyId])
REFERENCES [dbo].[Faculties] ([InstitutionUserId], [FacultyId])
Upvotes: 2
Reputation: 1269773
The keys should be in the same order that they are defined:
ALTER TABLE dbo.Educators
ADD CONSTRAINT FK_Educators_FacultyId_Faculties_FacultyId
FOREIGN KEY(InstitutionUserId, FacultyId)
REFERENCES dbo.Faculties(InstitutionUserId, FacultyId);
Upvotes: 1