简体   繁体   中英

Creating a foreign key to compound primary key

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?

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])

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM